HelloWorld, the first step in learning every language. Some people jokingly, these years of programming career is to learn the HelloWorld of various languages, do not know whether it is deprecating or self-deprecating. At present, the company uses Java as the main development language, I have been language conversion for half a year, this HelloWorld is the first language conversion. Fortunately, I learned a little bit at the undergraduate level, and before that, we had a lot of similarities between the long-time C + + development. The JDK installation and environment configuration (jdk 1.6.0.45) is omitted here, starting directly from the code.
First look at one of the simplest Java HelloWorld:
Public class HelloWorld { publicstaticvoid Main (String[]agrs) { System.out.println ("helloworld!" ); }}
Generally speaking, the beginner writes HelloWorld here, compiles the run once to see the result to be possible to end. Here is a little more exploration of this applet to learn more about the features in Java programming.
1. Encoding of source files
Originally for simplicity, I wrote and saved the code as Helloworld.java in Win7 with Notepad, and then javac the compiler directly with the command line. Because of the habit of writing Linux programs under Windows, I saved the code as a UTF-8 encoded Helloworld.java file while Notepad was saved. Compile-time prompt:
After careful examination of the source code to determine that there are no spelling errors, try to change the encoding back to Windows default ANSI, successfully generated the helloworld.class and be able to run correctly, it seems that the coding inconsistency. Next, holding the mentality of trying, using Unicode and Unicode Big endian save the source code, found also will error, just hint different, the compiler hints that there are illegal characters. This issue does not occur if you save the file by default in Eclipse.
Interestingly, if you use Java's I/O method to generate a text file, how to determine the encoding of the file is also a common problem. If the encoding difference is only involved in the Windows/linux two platforms, not the Chinese encoding, the former uses \ r \ n and the latter uses \n\r or \ n. For Chinese character coding, you need to specify the encoding in the I/O method used, which is no longer detailed in one step.
2. Why is there no import statement?
Remember classic K&r classic HelloWorld? Even with minimal effort, C still avoids the use of # include <stdio.h> to introduce header files in order to use the printf function.
Unlike Java and C + +, this simple HelloWorld does not require an import like include, and it does not need to use namespaces, which may seem simpler. In fact, this is because Java to each Java file is imported by default Java.lang this package, thus eliminating the import Java.lang; In this way, the screen output below is directly using SYSTEM.OUT.PRINTLN ().
Java.lang includes all the commonly used classes and methods, the specific content readers are interested in self-access. The above mentioned Java.import is "default import", is there any way to prohibit its import? I searched the next, not yet found the relevant information, if any readers understand, hope to tell me. (This may involve problems with ClassLoader, not yet researched)
If you insist on using the package with import in this simple code, you can refer to section sixth of this article.
3. Why is the file name consistent with the class name? Class name and modifier issues
As can be seen in practice, the compilation result is Helloworld.class, but the command running is Java HelloWorld. If there are more classes in this file, you can see that these classes generate *.class files at compile time. The question of "consistent class name and file name" does not make sense, obviously when code is written, there can be a number of classes in a file. This is related to the Java features (from the Java Programming Idea (fourth edition Chinese version)):
Each compilation unit (file) can have at most one public class, and if so, its name must match the file name that contains the compilation unit, including casing.
If you do not follow this requirement, write code similar to the following
// error in CODE public class HelloWorld { public static void Main (String[]agrs) {System.out.println ( "helloworld!" ); }} public class HelloWorld2 { public static Span style= "color: #0000ff;" >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, the program can run normally, only Helloworld.main () is executed at this time, and no conflict will occur.
In fact, if the file has only one HelloWorld class, or there are two classes, as long as the class name that includes main () is consistent with the file name, the class name is not public, and it is called the main () method of the class that is consistent with the file name. But personally think this is not a good programming practice, as follows:
class HelloWorld { publicstaticvoid Main (String[]agrs) { System.out.println ("helloworld!" ); }} class HelloWorld2 { publicstaticvoid Main (String[]agrs) { System.out.println ("HelloWorld, Me Too!" ); }}
At compile time, Helloworld.class and Helloworld2.class are generated, respectively, and the result is two classes of their respective main () methods.
parameter tables and modifiers for 4.main () functions
In C, there are a lot of details to be noted for the modifier and parameter table for main () (refer to a variety of main ()). For Java, the writing of Main () is also a simple exploration.
First look at the parameter table string args[]. Although compiler requirements must be this form, if you do not use the standard form and other forms such as int x, String s as the parameter table, the compilation is possible, but at the execution of the exception will be thrown, regardless of whether the parameters are provided:
Nosuchmethoderror the table name, expecting the main () method with a parameter of string args[]. Although a method with the same name is provided, the overloaded mechanism of the method does not replace the expected main (String args[]) method.
Next look at the modifier public. In the 3rd article has already mentioned the public to the class name adornment has the explanation, but for main () this and the file same name class's member method, in order to be able to be called, can only use the public to decorate. Do not use modifiers (package access rights), use private or protected to prompt:
For modifier static, it indicates that this method is stored in a static store and can be called without instantiating an object. After removing the static, you can compile the pass and prompt the runtime.
To further verify this, you can write a construction method to validate. (A constructor is a method that is called when an object of a class is instantiated)
Public class HelloWorld { hellowrold { System.out.println ("Constructor"); } Public Static void Main (STRING[]AGRS) { System.out.println ("helloworld!" ); }}
When you compile the runtime, you can see that the construction method is not running.
It is also necessary for modifier void. changing to int and adding the corresponding return statement will also prompt "Nosuchmethoderror:main". Introduced in the Java Virtual Machine specification (JavaSE7) (Zhou Zhiming, etc.)
The
startup of a Java virtual machine is accomplished by creating an initial class (Initial Class) by the bootstrap ClassLoader (Bootstrap class loader§5.3.1), which is specified by the virtual machine's implementation. Shortly thereafter, the Java Virtual machine links to this initial class, initializing and calling its public void main (string[]) method. The entire execution of the following is initiated by a call to this method.
As can be seen, void return values are also required and other forms are not allowed.
After further testing,Args[0] is the first parameter, whereas in C, Argv[0] is the name of the executed program.
5. Since the main () method is a class method ...
Since the main () method is a class method, it is natural to invoke this method again when instantiating an object of this class. Add two lines to the HelloWorld source code, as shown below
Public class HelloWorld { publicstaticvoid main (string[] args) { New HelloWorld (); System.out.println ("helloworld!" ); H.main (args);} }
Run the result as
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)
... ...
The HelloWorld is broken and the process of creating an object with infinite recursion causes a memory overflow.
6. Try the package
Of course, there are many more files to be processed when using Java more often. In order to organize files under the same namespace, you need to use a package. Corresponds to import, in order to specify which package the current file is in, add the packages statement. By adding a package name, the original code becomes
Import Test Public class HelloWorld { publicstaticvoid Main (String[]agrs) { System.out.println ("helloworld!" ); }}
After compiling, it cannot be run as shown in
In fact, the package name is an implicit directory structure. in order to run, you need to move Helloworld.class into the test folder of this path and run it as follows:
Summary
Can be seen, for a small helloworld, still have a lot of things to explore, just confined to the length and my level, this article just a brief introduction. The following are the topics presented in this article that can be further studied in the future, for reference only:
The choice of encoding method for 1.I/O methods
2. Package and Code organization
3.Java virtual Machine (JVM)
Related reading
Deep understanding of Java HelloWorld
Introduction to Java (i): Toss HelloWorld