aspose file tools*
The moose likes Beginning Java and the fly likes Why Java main method is static? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why Java main method is static?" Watch "Why Java main method is static?" New topic
Author

Why Java main method is static?

Srikantha Reddy Lankireddy
Greenhorn

Joined: Aug 30, 2007
Posts: 2
First of all I want to tell thanks to all persons who replied to my doubts.

The main method's signature in Java is

public static void main(String[] args) { ... }

It is public because outside process(JVM) need to access it to run it. It is void because it doesn't return any value. It takes String array as argument so that it can take command line arguments. But, why it should be static?

By defining it as static, JVM can invoke it without creating object for the enclosing class. But, JVM can create an object for the corresponding class and can invoke the main method then? Is there any strong reason for this?



The reason I got when searched on Internet says "JVM can not create any object before program runs. So, to run the program main should be invoked without creating any object. That's why main should be static."

But, I'm thinking that when JVM can load a class, why it can not create object before calling main method? after all JVM only creates and maintains all objects in our program.

Please somebody throw some light on this...
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42612
    
  65
The JVM has no business creating objects of the application's classes unless the application specifically tells it to. Creating an object may have all kinds of consequences that the JVM knows nothing about.

Also, the class may not have a no-argument constructor, making it impossible easily to create an object.


Ping & DNS - my free Android networking tools app
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why Java main method is static?