Java Program Structure

Hello, World program in Java

Here is a very simple Java program that prints out “Hello, World!” to the screen:

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

This text is stored in the file Hello.java. We will learn much more about what everything means as the course progresses, but for now let’s discuss each line separately:

  • public class Hello – this line begins a class in our program. For now, just remember that the name you give the class (in this case, “Hello”) must match the name of the file (in this case, “Hello.java”). Capitalization matters – we could not name the class “hello”.

  • { – this bracket opens up the class

  • public static void main(String[] args) – this line declares the main method for our program, which is where the program begins. For now, just copy this line into all your programs.

  • { – this bracket opens up the main method

  • System.out.println("Hello, World!"); – this line prints “Hello, World!” to the console

  • } – this bracket ends the main method

  • } – this line ends the class

Compiling Java programs

Once you have written a computer program, you need to compile it. This process does two things:

  • Checks to see if your program has any errors
  • Converts your program into an executable file that the computer can run

To compile your program, open the terminal in VS Code (View->Terminal). In the terminal, you can compile your program like this:

javac Name.java

(where Name.java is the name of your program). For example, to compile the Hello, World program you would do:

javac Hello.java

If your program has any errors, the compiler will print a list of what is wrong and where the problem is. If there are no errors, it will create the file Name.class (where Name is the name of the program file). For example when you compile the Hello, World program it will generate the file Hello.class.

If you get an error saying that the javac command is not recognized, please refer to the Tools guide in chapter 0.

Executing Java programs

After you have compiled your program in the VS Code terminal and generated a class file, then you are ready to run it. In the terminal, type:

java Name

where Name.class is the name of your class file. To run the Hello, World program you would type:

java Hello

to run the program.

Interactive Development Environments (IDEs)

For this class, we will write our programs in the VS Code text editor and compile and run from its terminal. Working with the terminal in particular will be a useful skill in other computer science courses and in the workplace.

However, if you are interested in trying out a more interactive development environment that with additional features such as a debugger, I recommend either IntelliJ or Eclipse.