Hello World Program in Java
Learn how to write your first Java program - Hello World. Understand the basic structure of a Java program with detailed explanation.
Method 1: Basic Hello World
The simplest form of Hello World program in Java.
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Hello, World!
Explanation
Let's break down each part:
- **public class Main**: Defines a public class named Main
- **public static void main(String[] args)**: The entry point of the program
- public: Accessible from anywhere
- static: Can be called without creating an object
- void: Returns nothing
- main: Method name
- String[] args: Command line arguments
- **System.out.println()**: Prints text to console with newline
Method 2: Using print() method
Using print() instead of println() - without newline.
public class Main {
public static void main(String[] args) {
System.out.print("Hello, ");
System.out.print("World!");
}
}Hello, World!
Explanation
The print() method outputs text without adding a newline at the end.
Multiple print() calls will output on the same line.
Method 3: Using printf() method
Using formatted output with printf().
public class Main {
public static void main(String[] args) {
String message = "World";
System.out.printf("Hello, %s!%n", message);
}
}Hello, World!
Explanation
printf() allows formatted output:
- %s: String placeholder
- %d: Integer placeholder
- %f: Float placeholder
- %n: Platform-independent newline
Frequently Asked Questions
What is Hello World program?
Hello World is traditionally the first program written when learning a new programming language. It simply prints "Hello, World!" to the console.
Why is the main method static?
The main method is static because JVM needs to call it without creating an object of the class. Static methods belong to the class, not instances.
What does public class mean?
The public keyword is an access modifier meaning the class is accessible from anywhere. A class is a blueprint for creating objects.
Try This Program
Copy this code and run it in our free online Java compiler.
Open Java Compiler