In this tutorial, you will learn how to write a simple Java program that prints “Hello World” to the console. You will also discover how to compile your Java code and run the resulting program.
“Hello World!” Program
Before we begin, ensure that your environment is set up to compile and run Java programs. If Java is not already installed, please follow the instructions to Install Java on your computer.
Writing HelloWorld.java
Open your preferred text editor (such as Notepad on Windows or Gedit on Ubuntu) and type the following code. Save the file as “HelloWorld.java”—the file name must match the class name defined in the code.
HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Compiling HelloWorld.java
Compilation is the process in which the Java compiler converts your source code into bytecode. This bytecode is then executed by the Java Runtime Environment (JRE), making Java programs platform independent.
To compile the program, navigate to the directory where HelloWorld.java
is saved and run the following command:
tutorialkart@java:~$ javac HelloWorld.java
If the compilation completes without errors, a .class
file (in this case, HelloWorld.class
) will be generated.
tutorialkart@java:~$ ls
HelloWorld.class HelloWorld.java
Running HelloWorld.class
Running the compiled .class
file loads the bytecode into the Java Runtime Environment (JRE), which executes the program instructions. To run your program, use the following command from the directory containing the .class
file:
tutorialkart@java:~$ java HelloWorld
Hello World
If the program executes correctly, you will see “Hello World” printed on the console.
Conclusion
In this tutorial, we successfully wrote, compiled, and executed a simple HelloWorld program.