Examining Hello World

Hello World is very close to the simplest program imaginable. Nonetheless there’s quite a lot going on in it. Let’s investigate it, line by line.

For now the initial class statement may be thought of as defining the program name, in this case HelloWorld. The compiler actually got the name for the class file from the class HelloWorld statement in the source code, not from the name of the source code file. If there is more than one class in a file, then the Java compiler will store each one in a separate .class file. For reasons we’ll see later it’s advisable to give the source code file the same name as the main class in the file plus the .java extension.

The initial class statement is actually quite a bit more than that since this “program” can be called not just from the command line but also by other parts of the same or different programs. We’ll see more in the section on classes and methods below.

The HelloWorld class contains one method, the main method. As in C the main method is where an application begins executing. The method is declared public meaning that the method can be called from anywhere. It is declared static meaning that all instances of this class share this one method. (If that last sentence was about as intelligible as Linear B, don’t worry. We’ll come back to it later.) It is declared void which means, as in C, that this method does not return a value. Finally we pass any command line arguments to the method in an array of Strings called args. In this simple program there aren’t any command line arguments though.

Finally when the main method is called it does exactly one thing: print “Hello World” to the standard output, generally a terminal monitor or console window of some sort. This is accomplished by the System.out.println method. To be more precise this is accomplished by calling the println() method of the static out field belonging to the System class; but for now we’ll just treat this as one method.

One final note: unlike the printf function in C the System.out.println method does append a newline at the end of its output. There’s no need to include a \n at the end of each string to break a line.

  1. What happens if you change the name of the source code file, e.g. HelloEarth.java instead of HelloWorld.java?
  2. What happens if you keep the name of the source code file the same (HelloWorld.java) but change the class’s name, e.g. class HelloEarth?

Comments are closed.