Your First Java Program: Hello World
Let us write the Hello World program, which prints a message on the screen. We will do it two times: first the classic way, which every Java book and every older project uses, and then the new short way of Java 25.
The classic Hello World
Save this in a file named Main.java. The name of the file must be the same as the name of the public class, with the same capital letters.
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Hello, World!
Understand each part
| Code | Meaning |
|---|---|
| public class Main | A class named Main. In Java all code lives inside classes |
| public static void main(String[] args) | The starting point. The JVM calls this method first |
| public | Anyone can call it (the JVM needs it) |
| static | It belongs to the class, so the JVM can call it without making an object |
| void | It does not return a value |
| String[] args | The command line arguments, as an array of text |
| System.out.println(…) | Prints the text and moves to a new line |
Compile and run in two steps
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
$ javac Main.java
$ java Main
Hello, World!
You can also run a single file in one step. Java compiles it in the memory and runs it at once:
$ java Main.java
Hello, World!
The short way in Java 25
Java 25 has compact source files and instance main methods. For small programs you do not need the class and the public static words. The class IO has easy print methods too:
void main() {
IO.println("Hello, World!");
}
Hello, World!
This is great for learning and for small scripts. For real projects, and for the rest of this tutorial, we mostly use the classic form, because you will see it in all the existing code.
print and println
public class Print {
public static void main(String[] args) {
System.out.print("Hello ");
System.out.print("World");
System.out.println("!");
System.out.println("Next line");
}
}
Hello World!
Next line
print stays on the same line, and println goes to the next line after the text.
Common beginner mistakes
- The class name and the file name are different (
Mainandmain.java). - A missing semicolon
;at the end of a statement. - Writing
system.out.printlnwith a smalls. Java is case sensitive. - A missing quote or bracket.
Here is what a missing semicolon looks like:
public class Oops {
public static void main(String[] args) {
System.out.println("Hello")
}
}
Oops.java:3: error: ';' expected
System.out.println("Hello")
^
1 error
error: compilation failed
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |