Simple example

Assuming that the “HelloWorld.java” contains the following Java source:

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

(For an explanation of the above code, please refer to http://stackoverflow.com/documentation/java/84/compile-and-run-your-first-java-program#t=201608210035544002048 .)

We can compile the above file using this command:

$ javac HelloWorld.java

This produces a file called “HelloWorld.class”, which we can then run as follows:

$ java HelloWorld
Hello world!

The key points to note from this example are:

  1. The source filename “HelloWorld.java” must match the class name in the source file … which is HelloWorld. If they don’t match, you will get a compilation error.
  2. The bytecode filename “HelloWorld.class” corresponds to the classname. If you were to rename the “HelloWorld.class”, you would get an error when your tried to run it.
  3. When running a Java application using java, you supply the classname NOT the bytecode filename.

Example with packages

Most practical Java code uses packages to organize the namespace for classes and reduce the risk of accidental class name collision.

If we wanted to declare the HelloWorld class in a package call com.example, the “HelloWorld.java” would contain the following Java source:

package com.example;

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

This source code file needs to stored in a directory tree whose structure corresponds to the package naming.

.    # the current directory (for this example)
|
 ----com
     |
      ----example
          |
           ----HelloWorld.java

We can compile the above file using this command:

$ javac com/example/HelloWorld.java