Print Page Print Page

Ch1- Hello World

  1. At command prompt, open a text editor and name the file For example, on Windows you might type the following,

While on Linux you might type


Of course, if you know how to use an IDE such as Eclipse feel free to do so instead.

  1. Create the class by typing the following.
public class Hello {
  1. Exit and save the program.
  2. Type javac to compile the program.
  3. Open again in your text editor.
  4. Create the main method and add the following code. This code goes between the class’s two braces.
public static void main(String[] args){
System.out.println("Hello, World!");
  1. Save the file. When back at the command-line compile and run the program.
$ javac
$ java Hello
Hello, World!

Note that if you get an error, read the error description for the cause and location. Open the file and fix the error. For example, the following error is due to misspelling the word “static” and therefore doesn’t compile.

JAMESs-Mac-mini:chapter_one jamesbrannan$ javac error:  expected
  public statoc void main (String[] args){
               ^ error: invalid method declaration; return type required
  public statoc void main (String[] args){
2 errors

Be certain to read the errors carefully, locate the error in the code, fix the error, and then recompile. After correcting “static” the program executes correctly.
Your finished code should appear as follows.

public class Hello {
  public static void main (String[] args){
    System.out.println("Hello World.");

Without fail, the hardest thing for beginning programmers to track are opening and closing braces. One mistake you might be tempted to make is to copy the code line for line from this tutorial. If you do this, you will most likely have problems remembering the closing brace. Instead, resolve to always type a closing brace immediately upon typing an opening brace. Then insert the code between the two braces. Also, indent code within braces. By following these two simple rules you will avoid many problems later when the exercises become more complex.

In the tutorials presented on this site I assume a *nix (Linux/Unix) environment with the nano text editor. However, you could just as easily use Windows. Moreover, you could replace nano with the editor of your choice. You are advised to use a text editor and the command-line for these exercises. Later you can use a full-featured IDE such as Eclipse or IntelliJ when you better understand Java.

If you are still uncertain as to writing and compiling a Java program from the command-line then here is an excellent video.  Although for Windows, it is essentially the same for *nix operating systems.