The main method
- Java course
- Beginner
- Lesson 2/116
- 4 min
Learn main(String[] args) and printing with System.out.println.
What is the main method?
Every Java program starts from the main method. This method is the entry point: when the JVM runs, it calls main first.
Its signature is:
public static void main(String[] args)Here public means accessibility, static means it is called at class level, void means it returns nothing. String[] args holds command-line parameters.
To print text to the screen you use System.out.println. It prints the output and moves the cursor to a new line.
println vs print
System.out.println moves the cursor to a new line after printing. System.out.print keeps it on the same line.
System.out.print("A");
System.out.print("B");
// Output: AB
System.out.println("A");
System.out.println("B");
// Output: A\nBUse println for separate lines and print for same-line output. Which one you choose depends on the format you want.
Practice Write your first Java program
Define a Main class with a main method. Inside main, print Hello with System.out.println.
Sample solution
public class Main {
public static void main(String[] args) {
System.out.println("Hello");
}
}Expected output
Hello
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What parameter does main take?
- String[] args Correct answer
- int x
- double[] data
- boolean flag
Explanation: main takes a String array: the command-line parameters.
2 Complete the println call
System.out.____("Hello");
System.out.println("Hello");
Explanation: System.out.println prints and moves to a new line.
3 Match the keywords
| Term | Meaning |
|---|---|
public |
Accessible |
static |
Class-level |
void |
No return |
String[] |
Parameter type |