Hello, World in Java
Problem
Hello World is the traditional first program written in any programming language, used to confirm the basic setup works.
Print "Hello, World!" to the console.
Java Program
public class HelloWorld {
public static void main(String[] args) {
// main() is the entry point the JVM looks for and calls first
System.out.println("Hello, World!");
}
}Output
Core Logic
It's the classic first program in any language — define the method the JVM looks for on startup, then print a line of text.
- 1
public class HelloWorlddeclares a class matching the file name, which Java requires for the public class in a file. - 2
public static void main(String[] args)is the exact method signature the JVM searches for and invokes first. - 3Inside
main,System.out.println(...)writes the given string to standard output. - 4
println(as opposed toprint) appends a newline after the text.
Hello, World!.Key Point: Every Java program needs this exact main signature — the JVM won't find an entry point without it.
Key Concepts
Approach 2: Using printf()
public class HelloWorldPrintf {
public static void main(String[] args) {
System.out.printf("Hello, World!%n"); // %n adds the newline printf doesn't add automatically
}
}
Output
Core Logic
printf() writes formatted output using a template string, which becomes useful the moment a program needs to mix in variable values.
- 1
System.out.printf("Hello, World!%n")takes a format string as its argument, the same wayprintlntakes plain text. - 2
%nis printf's placeholder for a platform-correct newline — printf doesn't add one automatically the wayprintlndoes. - 3With no other
%placeholders in the string, this call behaves just likeprintln, just written a different way.
System.out.printf("Hello, World!%n") prints the same single line as println("Hello, World!").Key Point: printf only pays off once a format string has real placeholders — System.out.printf("Hello, %s!%n", name) substitutes name into %s, something plain println can't do without manual string concatenation.
Key Concepts
Interview Questions
Why must main be public static void?
public lets the JVM call it from outside the class, static lets it run without creating an object first, and void means it returns nothing. The JVM looks for exactly that signature as the program's entry point.
Does the file name have to match the class name?
For a public class, yes: public class HelloWorld must be saved as HelloWorld.java. A non-public class can live in a file with any name.
Can you run Java without compiling first?
Since Java 11, java HelloWorld.java compiles and runs a single-file program in one step. Larger projects still use javac or a build tool.