Learn Pain Less

HomeOur TeamContact
Java
Why Main method in java is static?
Pawneshwer Gupta
Pawneshwer Gupta
March 17, 2015
1 min
Why Main method in java is static?

The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this:

public class JavaClass{
protected JavaClass(int x){}
public void main(String[] args){
}
}

Should the JVM call new JavaClass(int)?

What should it pass for x?

If not, should the JVM instantiate JavaClass without running any constructor method? I think it shouldn’t, because that will special-case your entire class - sometimes you have an instance that hasn’t been initialized, and you have to check for it in every method that could be called.

There are just too many edge cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. That’s why main is static.

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Tags

main methodcore java

Share


Pawneshwer Gupta

Pawneshwer Gupta

Software Developer

Pawneshwer Gupta works as a software engineer who is enthusiastic in creating efficient and innovative software solutions.

Expertise

Python
Flutter
Laravel
NodeJS

Social Media

Related Posts

Types of Java classes
Types of Java classes
March 19, 2015
1 min
Learn Pain Less  © 2024, All Rights Reserved.
Crafted with by Prolong Services

Quick Links

Advertise with usAbout UsContact Us

Social Media