1. Preliminaries, Environment
Hello World Java program:
public class Test {
public static void main(String [] args) {
System.out.println("Hello, World!");
}
}
Note there is no semicolon at the end (unlike in C++).
Important points:
- This needs to be in a file called Test.java. Any public class needs to be in a file by the same name. (Yes, this means there can be only one public class per file.)
- You can compile it with "javac Test.java". You will get out a file Test.class. You can run this with "java Test". Or you can use an IDE. Any class that contains a main method with the above signature can be run as the main class of an application by just giving its name to the "java" command, which invokes the Java Virtual Machine.
The above is in a "package" (the Java notion for namespaces) called the "default package". It's nameless. You could put your class in a package, say, "mypack" by adding the line "
package mypack;" at the beginning of the file. Packages are hierarchical and are typically the way to organize libraries or applications. They correspond to directories in the file system. If the above class was in a directory "
myFirstExamples", which was itself under a directory "
myJavaCode", we could add the class in a corresponding package "
myJavaCode.myFirstExamples":
package myJavaCode.myFirstExamples;
public class Test {
public static void main(String [] args) {
System.out.println("Hello, World!");
}
}
In this case, you can still compile the file from the directory it's in using "javac Test.java". But when you try to run it using "java Test" you will receive a message such as "Exception in thread "main" java.lang.NoClassDefFoundError: Test (wrong name: myJavaCode/myFirstExamples/Test)".
The class can be run if you go to the parent directory of "myJavaCode" and use "java myJavaCode.myFirstExamples". You can also add that parent directory to your Java CLASSPATH (an environment variable in your shell, or a variable in your IDE). But your class's name is now "myJavaCode.myFirstExamples.Test", not just "Test". This is how other code (outside this package) will refer to it.
The package mechanism is something you need to employ when you use functionality from the Java libraries. Look at the
documentation of the standard library. (You should do this often, by the way!) Locate a class, say class Dialog. Notice the "java.awt" prefix before the name of the class. To use this class, you can either refer to it by its full name ("java.awt.Dialog"), or you can write "
import java.awt.*;" at the top of your program (which will let you use any name from the java.awt package without qualifying it), or you can be explicit and say "import java.awt.Dialog;" (which will only let you use this class without qualification).