Overview
The Hello World program is traditionally the first program you write in any language.
It prints one line of text and shows the minimum structure every Java program needs:
a class, a main() method and a statement.
Save this file as HelloWorld.java. The file name must exactly match the public class name, including capital letters.
Step-by-Step Explanation
1
Class Declaration
Every Java program lives inside a class.
public class HelloWorld {
...
}
public is an access modifier, class is the keyword that defines a class, and HelloWorld is its name.
The curly braces { } mark where the class starts and ends.
2
The main() Method
The entry point of the program.
public static void main(String[] args)
When you run the program, the JVM (Java Virtual Machine) looks for this exact method and starts running from here.
3
Print Statement
Displays text on the screen.
System.out.println("Hello World");
System is a built-in class, out is the standard output stream (the console), and println() prints the text and moves to a new line.
Text in double quotes is a String, and the statement ends with a semicolon ;.
Parts of the main() Method
| Keyword |
Meaning |
public |
The JVM can call this method from outside the class. |
static |
The method runs without creating an object of the class. |
void |
The method doesn't return a value. |
main |
The method name the JVM looks for to start the program. |
String[] args |
Holds command-line arguments, if any are passed. |
How a Java Program Runs
javac compiles your source code into bytecode (HelloWorld.class).
The java command then runs that bytecode on the JVM. That's why the same .class file runs on Windows, Linux and macOS.
javac HelloWorld.java
java HelloWorld
Output
Hello World
Common Mistakes
Missing the class keyword
Writing HelloWorld { without public class gives a compile error such as class, interface, enum, or record expected.
File name doesn't match the class name
A public class named HelloWorld must be saved in HelloWorld.java, not helloworld.java or Main.java.
Wrong capitalisation
Java is case-sensitive. system.out.println or Main won't work.
Adding .class when running
java HelloWorld.class fails. Run it with java HelloWorld.
Tip for Java 11 and later
You can skip the compile step for a single file and run java HelloWorld.java directly.
Key Takeaway
Every Java program needs a class and a main() method.
Compile with javac, run with java, and print output with System.out.println().