Hello, World!
By tradition, the first program in any language just prints Hello, World!. Here it is in Java:
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Output
Hello, World!
That's a lot of words just to print one line! Don't worry – you don't need to understand every word yet. Here is what each part means in simple terms:
| Part | What it means |
|---|---|
public class Main | Our program is called Main. In Java, all code lives inside a class. |
{ } | Curly brackets mark where something starts and ends, like the cover of a book. |
public static void main(String[] args) | The main method: the place where the program starts. Java always begins here. |
System.out.println(...) | Print something on the screen, then move to a new line. |
; | A semicolon ends each instruction, like a full stop ends a sentence. |
Think of it like this: Think of
class Mainas a house andmainas its front door. When Java runs your program, it always walks in through the front door first.
Every program has the same frame
For now, every program you write will look like this. You only change the lines inside main:
public class Main {
public static void main(String[] args) {
System.out.println("I am learning Java.");
System.out.println("This is fun!");
}
}Output
I am learning Java. This is fun!
Java runs the lines from top to bottom, one after another.
Common mistake: Java is case-sensitive:
Systemis not the same assystem, andMainis notmain. Copy the capital letters exactly.
What if I forget the semicolon?
Java refuses to run the program and tells you where the problem is:
public class Main {
public static void main(String[] args) {
System.out.println("Hello")
}
}Output (the program does not compile)
Main.java:3: error: ';' expected
System.out.println("Hello")
^Read the message: Main.java:3 means “file Main.java, line 3”, and ';' expected means “I expected a semicolon here”. Java error messages look scary at first but they are usually very helpful.