Java entry notes (1): Tossing HelloWorld and javahelloworld

Source: Internet
Author: User

Java entry notes (1): Tossing HelloWorld and javahelloworld

HelloWorld: the first step to learn every language. Some people say that these years of programming career is to learn the HelloWorld of various languages. Currently, my company uses Java as the main development language. I have been performing language conversion for more than half a year. HelloWorld is the first level of language conversion. Fortunately, I have learned so much in my undergraduate course, and I have been developing C/C ++ for a long time. There are many similarities between them. Here, we will skip JDK installation and environment configuration (JDK 1.6.0.45) and start with the code.

First, let's look at HelloWorld in the simplest Java:

public class HelloWorld {  public static void main(String[]agrs)    {      System.out.println("HelloWorld!");    }}

Generally, when a beginner writes HelloWorld, the compilation and running result can be completed. Next, we will explore this small program to learn more about and learn the features of Java programming.

 

1. encoding of source code files

For the sake of simplicity, I wrote and saved the code HelloWorld. java in notepad in Win7, and then compiled it directly using the command line javac. Out of the habit of writing Linux programs in Windows, I saved the code as a UTF-8-encoded HelloWorld. java file when saving it in notepad. Compile prompt:

After carefully checking the source code to confirm that there are no spelling errors, try to change the encoding back to the default ANSI in Windows, and successfully generate HelloWorld. class and run it correctly. It seems that the encoding inconsistency has caused the fault. Next, we will try to use Unicode and Unicode Big Endian to save the source code, and we will also report an error, except that the compiler prompts that there are invalid characters. This problem does not occur if files are saved by default in Eclipse.

Interestingly, if you use the Java I/O method to generate a text file, how to determine the file encoding is also a common problem. If it only involves the encoding differences between Windows and Linux platforms, but does not include Chinese encoding, the former uses \ r \ n, and the latter uses \ n \ r or \ n. For Chinese character encoding, You need to specify the encoding in the used I/O method. Here we will not detail it in detail.

 

2. Why is there no import statement?

Do you still remember the classic HelloWorld in K & R? Even if it is extremely streamlined, the # include <stdio. h> header file cannot be used in C to use the printf function.

Java and C/C ++ are different. This simple HelloWorld does not need an import similar to the include statement, nor does it need a namespace. It seems simpler. In fact, this is because Java imports the Java. lang package to every java file by default, saving the need to import java. lang. In this way, you can directly use System. out. println () for screen output below.

Java. lang includes common classes and methods. For details, refer to them. As mentioned above, java. import is "Default import". Is there any way to disable it from being imported? I searched and haven't found any relevant information yet. If anyone knows this, I hope I can tell you. (This may involve the classloader issue, which has not been studied yet)

If you insist on using the package corresponding to the import in this simple code, refer to Section 6 of this article.

 

3. Why should the file name be consistent with the class name? Class Name and modifier Problems

In practice, we can see that the compilation result is HelloWorld. class, but the running command is java HelloWorld. If there are more classes in this file, we can see that these classes generate *. class files during compilation. It is not reasonable to raise the question "the class name and file name are consistent". Obviously, there are many classes in a file during code writing. This involves Java features (from Java programming ideas (Chinese Version 4):

Each compilation unit (File) can have only one public class. If yes, its name must match the file name containing the compilation unit, including the case.

If you do not comply with this requirement, write the code similar to the following:

//ERROR IN CODEpublic class HelloWorld {  public static void main(String[]agrs)    {      System.out.println("HelloWorld!");    }}public class HelloWorld2 {  public static void main(String[]agrs)    {      System.out.println("HelloWorld, me too!");    }}

Then the compiler will prompt this

If the public of the HelloWorld2 class is removed, it becomes the package access permission, and the program can run normally. At this time, only HelloWorld. main () is executed, and no conflict occurs.

In fact, if this file has only one HelloWorld class, or there are two classes, as long as the class name including main () is the same as the file name, it can run normally without adding public before the class name, the main () method of the class that is consistent with the file name is called. But I personally think this is not a good programming practice, as follows:

class HelloWorld {  public static void main(String[]agrs)    {      System.out.println("HelloWorld!");    }}class HelloWorld2 {  public static void main(String[]agrs)    {      System.out.println("HelloWorld, me too!");    }}

During compilation, HelloWorld. class and HelloWorld2.class are generated. When they are run separately, the result is the main () method of the two classes.

 

4. Parameters and modifiers of the main () function

In C, there are many details about the modifier and parameter table of main () (you can refer to a wide variety of main ()). For Java, the main () method is also briefly explored here.

First, let's look at the parameter table String args []. Although the compiler requires this form, if you do not use the standard form and use other forms such as int x and String s as the parameter table, compilation can pass, however, an exception is thrown during execution, regardless of whether the parameter is provided:

NoSuchMethodError table name. The expected parameter is the main () method of String args.Although a method with the same name is provided, the method overload mechanism cannot replace the expected main (String args []) method.

Next, let's take a look at the modifier public. The modification of the class name by public has been mentioned in Article 3rd. For the member method of the class with the same name as the file main (), only public can be used for modification to be called. If you do not use a modifier (package access permission) or use private or protected, the following message is displayed:

The modifier static indicates that this method is stored in the static storage area and can be called without instantiating an object. After static is removed, it can be compiled and run as prompted.

To further verify this, you can write a constructor to verify it. (Constructor is the method called when the class object is instantiated)

public class HelloWorld {    HelloWrold    {        System.out.println("Constructor");    }    public static void main(String[]agrs)    {      System.out.println("HelloWorld!");    }}

  During compilation and running, we can see that the constructor is not running.

The modifier void is also required. If you change the value to int and add the corresponding return statement, the message "NoSuchMethodError: main" is displayed ". This article introduces the Java Virtual Machine specification (E7) (translated by Zhou Zhiming ).

The startup of a Java Virtual Machine is accomplished by creating an Initial Class (Initial Class) through the Bootstrap Class Loader (Bootstrap Class Loader § 5. 3.1), which is specified by the specific implementation of the virtual machine. Then, the Java Virtual Machine links this initial class, initializes and calls its public void main (String []) method. The subsequent execution process starts with the call to this method.

It can be seen that the return value of void is also required, and Other forms are not allowed.

Further tests show that,Args [0] is the first parameter. In C, argv [0] is the name of the program to be executed.

 

5. Since the main () method is a class method ......

  Since the main () method is a class method, you can call this method again when instantiating the class object. Add two lines to the HelloWorld source code, as shown below:

public class HelloWorld {  public static void main(String[] args)    {        HelloWorld h = new HelloWorld();        System.out.println("HelloWorld!");        h.main(args);    }}

The running result is

HelloWorld!

HelloWorld!

HelloWorld!

... ...
HelloWorld!
Exception in thread "main" java.lang.StackOverflowError
at sun.nio.cs.ext.DoubleByteEncoder.encodeLoop(Unknown Source)
at java.nio.charset.CharsetEncoder.encode(Unknown Source)
at sun.nio.cs.StreamEncoder.implWrite(Unknown Source)
at sun.nio.cs.StreamEncoder.write(Unknown Source)
at java.io.OutputStreamWriter.write(Unknown Source)
at java.io.BufferedWriter.flushBuffer(Unknown Source)
at java.io.PrintStream.write(Unknown Source)
at java.io.PrintStream.print(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at main.HelloWorld.main(HelloWorld.java:15)
at main.HelloWorld.main(HelloWorld.java:16)
at main.HelloWorld.main(HelloWorld.java:16)
at main.HelloWorld.main(HelloWorld.java:16)
... ...

It can be seen that HelloWorld is playing bad, and the infinite recursion process of object creation causes memory overflow.

 

6. Try package.

Of course, when you use more java, you often have to process multiple files. To organize files in the same namespace, you need to use a package. Corresponding to import. to specify the package in which the current file is located, you must add the package statement. Add a package name. The initial code becomes

import testpublic class HelloWorld {  public static void main(String[]agrs)    {      System.out.println("HelloWorld!");    }}

Compilation fails, as shown in

In fact, the package name is an implicit directory structure. To run the program, you need to move HelloWorld. class to the test folder in this path and run it as follows:

 

Summary

It can be seen that there are still many things to explore for a small HelloWorld, but it is limited by space and personal level. This article only gives a brief introduction. The following are the topics proposed in this article that can be further explored in the future, for your reference only:

1. I/O Method encoding method selection

2. Package and Code Organization

3. Java Virtual Machine (JVM)

 

Reading

Java HelloWorld

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.