Hello World - Your First Program
Write and understand your first Java program: the anatomy of a class, the main method, and printing output.
Overview
Key Points
- •Every Java program must have at least one class; the class name must match the filename
- •Execution starts at public static void main(String[] args) - this exact signature is required
- •System.out.println() prints a line and moves the cursor to the next line
- •System.out.print() prints without adding a newline at the end
- •System.out.printf() prints formatted output using format specifiers like %s and %d
- •Java is case-sensitive: Main, main, and MAIN are all different identifiers
Examples
The classic Hello World program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}public class HelloWorld - the class must be public and match the filename (HelloWorld.java).
Difference between println, print, and printf
public class PrintDemo {
public static void main(String[] args) {
System.out.println("Line 1"); // prints + newline
System.out.println("Line 2");
System.out.print("No "); // no newline
System.out.print("newline\n"); // manual newline
System.out.printf("Hello, %s! You are %d years old.%n", "Alice", 25);
}
}\n is an escape sequence for a newline character. %n in printf also adds a platform-correct newline.
Anatomy of the main method - each keyword explained
public class Anatomy {
// ↓ accessible from outside the class
// public
// ↓ belongs to the class, not an object
// static
// ↓ returns nothing
// void
// ↓ the method name Java looks for
// main
// ↓ command-line arguments
// (String[] args)
public static void main(String[] args) {
System.out.println("I understand main!");
}
}All four parts - public, static, void, main - must be present and in the correct order.
Common Mistakes
- Writing `System.out.Println` with a capital P - Java is case-sensitive; it must be `println`
- Forgetting the semicolon at the end of a statement - every statement in Java ends with ;
- Class name mismatch: if the class is `HelloWorld` but the file is `helloworld.java`, compilation will fail
Note
In IntelliJ IDEA, type `sout` and press Tab - it auto-expands to `System.out.println()`. This shortcut saves a lot of typing.
Exercises
Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4