🚀 Declaration of main
Method
public static void main(String[] args)
🧠Why Is main
Static?
- Avoids Object Creation at Launch
- The JVM needs a starting point to run your program.
- If
main
weren’tstatic
, it would require creating an object of the class first. - But creating that object would need a method to start with… creating a paradox!
- Declaring it
static
solves this: JVM can callmain()
directly using the class name.
- Program Entry Point Must Be Fixed
- Java needs a known, consistent method signature as the program’s entry.
- Making it
static
ensures it’s tied to the class itself, not an instance.
- Memory Efficiency
- No need to allocate memory to an object just to begin execution.
- Only one copy of the
main()
method exists per class, as it belongs to the class, not instances.
- Method Binding at Compile-Time
- Static methods use early binding (compile-time binding), improving speed during startup.
🧾 Bonus: What If You Remove static
?
If you write:
public void main(String[] args)
- The program compiles, but it won’t run, and you’ll get:
Error: Main method not found in class…
Because JVM specifically looks for:
public static void main(String[] args)
🧠Interview Takeaways
Concept | Explanation |
---|---|
Why static ? | To invoke main() without object creation |
Who calls main() ? | Java Virtual Machine (JVM) |
What happens if not static? | Compile-time success, but runtime failure due to missing entry point |
Memory & Speed Benefit | No object overhead; faster load time via early binding |