Creating Hello World in Java
The following Java program prints the text Hello world
to the screen, followed by Hello again
on the next line.
Creating and running the program
To create the program, open your text editor and create a new file titled HelloWorld.java
. Then copy and paste the following code.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world");
System.out.println("Hello again");
}
}
To run the program, go to the command line and type:
javac Helloworld.java
Output:
Hello world
Hello again
How the program works
Lines 3 and 4 of the program print the two lines of text, using the command System.out.println
. Later, you will understand why this command is named the way it is and why the periods are used in the command. Notice that there is a separate command to print each line, and each line is separated by a semicolon.
Lines 1 and 2 of the program are needed, due to the requirements for the way Java programs are organized:
Line 1 declares a class, which groups functions that are related. Every Java program must contain at least one class, and each class is stored in a separate file. The name of HelloWorld.
Line 2 declares a method, which is a function within a class. Every Java program must have a main method. This is the place where the program begins execution.
Classes usually contain multiple methods. Since this is the most basic case, only the main method is included.
Later, you will learn about classes and methods in much more detail.