O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Hello World

As long ago as 1978, Brian Kernighan and Dennis Ritchie wrote, in their classic book The C Programming Language, that “the first program to write is the same for all languages.” They were referring, of course, to the “Hello World” program. The Java implementation of Hello World is shown in Example 1-1.

Example 1-1. Hello.java

package je3.basics;                          // A unique class name prefix
public class Hello {                         // Everything in Java is a class
    public static void main(String[  ] args) { // All programs must have main( )
        System.out.println("Hello World!");  // Say hello!
    }                                        // This marks the end of main( )
}                                            // Marks the end of the class

The first line of this program is the package declaration. It specifies the name of the package of which this program is part. The program’s name (as we’ll see in the second line) is Hello. The package name is je3.basics. We can combine these two names to produce a fully qualified name, je3.basics.Hello. Using packages provides a unique namespace for every Java program. By placing this Hello program in a package, I’ve helped to ensure that no naming conflict will arise if someone else defines a program that is also named Hello. Each chapter of this book has its own package that begins with the prefix je3 (for JavaExamples3). In this case, since this is the basics chapter, the package name is je3.basics.[1]

The value of “Hello World” is that it is a template that you can expand on in your later experiments with Java. The second and third lines of Example 1-1 are a required part of the template. Every program—every piece of Java code, really—you write is a class. The second line of the example says that we’re writing a class named Hello. It also says the class is public, which means it can be used by anyone.

Every standalone Java program requires a main( ) method. This is where the Java interpreter begins running a Java program. The third line of the example declares this main( ) method. It says that the method is public, that it has no return value (i.e., its return value is void), and that it is passed an array of strings as its argument. The name of the array is args. The line also says that main( ) is a static method. (In this chapter, we work exclusively with static methods. In Chapter 2, when we start working with objects, you’ll learn what a static method is, and you’ll see that nonstatic methods are actually the norm.)

In any case, you might as well go ahead and memorize this line:

public static void main(String[  ] args)

Every standalone Java program you ever write contains a line that looks exactly like this one. (Actually, you can name the array of strings anything you want, but it is usually called args.)

The fifth and sixth lines of Example 1-1 simply mark the end of the main( ) method and of the Hello class. Like most modern programming languages, Java is a block-structured language. This means that such things as classes and methods have bodies that comprise a “block” of code. In Java, the beginning of a block is marked by a {, and the end is marked by a matching }. Method blocks are always defined within class blocks, and as we’ll see in later examples, method blocks can contain such things as if statements and for loops that form subblocks within the method. Furthermore, these sorts of statement blocks can be nested arbitrarily deep within each other.

The first three lines and the last two lines of Example 1-1 are part of the basic framework of a Java application. It is the fourth line of the example that is of primary interest to us. This is the line that prints the words “Hello World!” The System.out.println( ) method sends a line of output to “standard output,” which is usually the screen. This method is used throughout this chapter and in many other chapters in this book. It isn’t until Chapter 3, however, that you’ll really understand what it is doing. If you are curious before then, look up the java.lang.System and java.io.PrintStream classes in Java in a Nutshell (or some other Java reference manual).

One final point to note about this program is the use of comments. Example 1-1 uses C++-style comments that begin with // and continue until the end of the line. Thus, anything between the // characters and the end of a line is ignored by the Java compiler. You’ll find that the examples in this book are thoroughly commented. The code and the comments are worth studying because the comments often draw your attention to points that are not mentioned in the main text of the book.

Running Hello World

The first step in running our program is to type it in.[2] Using a text editor, type in the Hello program as shown in Example 1-1. For now, however, omit the package declaration on the first line. Save the program in a file named Hello.java.

The second step is to compile the program. If you are using the Java Software Development Kit (SDK) from Sun, you compile code with the javac command.[3] cd to the directory that contains your Hello.java file, and type this command (assuming that javac is in your path):

% javac Hello.java

If the Java SDK has been properly installed, javac runs for a short while and then produces a file named Hello.class. This file contains the compiled version of the program. As I said earlier, everything you write in Java is a class, as the .class extension on this file indicates. One important rule about compiling Java programs is that the name of the file minus the .java extension must match the name of the class defined in the file. Thus, if you typed in Example 1-1 and saved it in a file named HelloWorld.java, you would not be able to compile it.

To run the program (again using the Java SDK) type:

% java Hello

This command should produce the output:

Hello World!

The java command is the Java interpreter; it runs the Java Virtual Machine. You pass java the name of the class that you want to run. Note that you are specifying the class name, Hello, not the name of the file, Hello.class, that contains the compiled class.

The previous steps have shown you how to compile and run Java programs that don’t have package declarations. If you omitted the package declaration when you typed in Hello.java, these instructions should have worked for you (if they didn’t, check that you typed the program in correctly). In practice, however, all nontrivial Java programs (including the examples in this book) do have package declarations. Using packages makes compiling and running Java programs a bit more complicated. As I just noted, a Java program must be saved in a file that has a name that matches the class name. When a class is in a package, there is a further requirement that the class be saved in a directory that matches the name of the package.

Go ahead and reinsert the package declaration into Hello.java:

package je3.basics;

Now make yourself a new directory (or folder) in which you’ll do all your work with the examples from this book. For example, on a Windows system, you might create a folder named c:\Examples. On a Linux system, you might use ~/Examples. Within this directory, create a subdirectory named je3. Then create a subdirectory of je3 named basics. Now copy your Hello.java program (with the package declaration) into this directory. On a Windows system, the resulting file might be:

c:\Examples\je3\basics\Hello.java

After you’ve created the directory structure and put your Java program in it, the next step is to tell the Java compiler and interpreter where to find it. The compiler and interpreter simply need to know the base directory you’ve chosen; they will look for the Hello.class file in subdirectories of this base directory, based on the package name. To tell Java where to look, you have to set the CLASSPATH environment variable in the manner appropriate for your operating system. If you used the suggested name for your base directory on a Windows system (c:\Examples), you can use a command like the following:

C:\> set CLASSPATH=.;c:\Examples

This tells Java to look first for classes in the current directory (.), followed by the c:\Examples directory.

On a Unix system using the csh shell, you can use the following command:

% setenv CLASSPATH .:/home/david/Examples

With the sh or bash shell, the command is:

$ CLASSPATH=.:/home/david/Examples; export CLASSPATH

You may want to automate this process by setting CLASSPATH in a startup file, such as autoexec.bat on Windows systems or .cshrc on Unix systems (under csh).

With your CLASSPATH set, you can now go ahead and compile and run the Hello program. To compile, change directories to the examples/basics directory that holds Hello.java. Compile the program as before:

% javac Hello.java

This creates the Hello.class file.

To run the program, you invoke the Java interpreter as before, but now you must specify the fully qualified name of the program, so that the interpreter knows exactly which program you want to run:

% java je3.basics.Hello

Because you’ve set the CLASSPATH, you can run the Java interpreter from any directory on your system, and it will always find the correct program. If you get tired of typing such long class names, you may want to write yourself a batch file or shell script that automates the process for you.

Note that all Java programs are compiled and run in this way, so we won’t go through these individual steps again. Of course, one step you don’t have to repeat is typing in all the examples. You can download the example source code from http://www.davidflanagan.com/javaexamples3.



[1] In the second edition of this book, I was more rigorous about preventing naming conflicts: I created the package name by reversing my Internet domain name, a procedure that should guarantee that there will be no naming conflicts. The resulting package name for this chapter was com.davidflanagan.examples.basics. For this edition, I’ve settled on a less rigorous but much easier to type alternative.

[2] Although this example is included in the online example archive, I’m suggesting that you type it in so that you start imprinting basic Java idioms in your brain. I’m also going to have you modify the example, in order to explain certain aspects of running the program.

[3] If you are using some other Java programming environment, read and follow the vendor’s instructions for compiling and running programs.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required