Java Examples in a Nutshell Notes

Java Basics

Hello World

Contents of Hello.java

  • Set Up
  • Compile & Run
    • To compile, open the Command Processor (command) window (Windows Start Menu > cmd > Enter), change to the directory with your java file, and type javac [filename].java. This creates a compiled version of the program, with the extension class, e.g., Hello.class.
    • To run the program, type java [filename], e.g., java Hello. In the command window, Hello World! will appear on a new line.
    • Tip: The name of the file minus the java extension must match the name of the class defined in the file. Also, the class must be saved in a directory that matches the name of the package, e.g., C:\Workspace\je3\basics.
  • About the Program
    • The package declaration (package je3.basics;) specifies the name of the package of which this program is part.
    • The public class (public class Hello) specifies the program name (Hello) and that it can be used by anyone (public).
    • Combining the package declaration and the program name (je3.basics.Hello) produces a fully qualified name. Placing the program in a package helps ensure that no naming conflict will arise of someone else defines a program that is also named Hello.
    • Every standalone Java program requires a main method (public static void main(String [ ] args) {). This is where the Java interpreter begins running the program. This line also says that the method is public and that it has no return value, i.e., its return value is void and that it is passsed an array of strings as its argument ((String [ ] args) {). The name of the array is args (can be anything but is commonly called args). The line also says that main( ) is a static method. Nonstatic methods are actually the norm.
    • 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 }. Method blocks are always defined within class blocks.
    • The System.out.println() method sends a line of output to the standard output, which is usually the screen.