This content originally appeared on DEV Community and was authored by Mohamad mhana
Introduction
Have you ever opened a fresh Java file and seen this line staring at you?
public static void main(String[] args) {
// code here
}
It looks⦠complicated.
Why all these words? Why not just main() like in other languages?
If youβve ever wondered why the Java main method looks so weird, youβre not alone. In this post, Iβll break it down piece by piece so youβll never have to memorize it blindly again.
The Role of the main Method
The main method is the entry point of any Java program.
When you run your program, the Java Virtual Machine (JVM) looks for this exact method signature to start execution.
Without it, your code has no starting point.
Breaking Down the Weirdness
Letβs decode each keyword in public static void main(String[] args) step by step:
- public β Access from Anywhere
public means this method is visible to the JVM (and everything else).
If it werenβt public, the JVM couldnβt call it.
Think of it as leaving your front door open for the JVM to enter your program.
- static β No Objects Needed
static means the method belongs to the class, not an object.
The JVM can call it without creating an object first.
Imagine if you had to new an object every time you wanted to run your program β painful!
- void β No Return Value
void means the method doesnβt return anything.
The JVM just needs a starting point to run your program β it doesnβt expect a result back.
- main β The Name Matters
The JVM specifically looks for a method called main.
If you rename it to start or helloWorld, your program wonβt run.
- String[] args β Command-Line Data
This is how your program can accept input from the command line.
Example:
public class Main {
public static void main(String[] args) {
System.out.println("First argument: " + args[0]);
}
}
If you run:
java Main hello
Output: First argument: hello
Why It Looks So Weird (Compared to Other Languages)
In Python, you just write:
print("Hello, world!")
In C, you write:
int main() {
return 0;
}
But Java is object-oriented from the ground up.
Thatβs why public static void main(String[] args)
has to carry extra keywords β to satisfy Javaβs strict rules.
Quick Memory Trick
Public β Let the JVM in
Static β No object needed
Void β Donβt return anything
Main β JVMβs entry point
String[] args β Extra data from the outside world
Further Resources
Official Java Documentation
(Geeks For Geeks): Java main() method
Conclusion
Yes, the Java main method looks weird at first.
But once you break it down, each keyword makes perfect sense.
Next time you see it, youβll know:
Why it has to be public
Why itβs static
Why it returns nothing
And how it handles external data
Your turn: Whatβs one Java keyword (final, static, super, etc.) that always confused you? Drop it in the comments β maybe Iβll cover it in the next post!
This content originally appeared on DEV Community and was authored by Mohamad mhana