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:
HelloWorld
. If they don’t match, you will get a compilation error.java
, you supply the classname NOT the bytecode filename.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