Wednesday 9 March 2016

Why main() method is static in java?

Being  a java programmer you must be aware that main() method is entry point for any java program.

Whenever you write any class and then run it, JVM (Java Virtual Machine) immediately looks for public static void main(String[] args) method in that class.

Now suppose, if you don't make main() method static then what wrong would happen?

static keyword in main() gives licence to JVM to access it without making instance of the class you are executing.

In absence of static keyword, it would have become necessary for JVM to first make an instance of the class containing main() method and then use that instance to call main() method of that class.

Now let's look at the scenario with an example;

public class check {

public void main(String args[]){              // static missing 

System.out.println("Checking without static");

}
}

Points to be noted here :
  • If we don't write static keyword with main() method, you won't get any compile time error. Reason for the same is that main() method can be overloaded in java. (Click to Learn how?) . Here overloaded version of main() is used.
  • But when you run it in Eclipse,   
  1.  A pop up window will open with message : "Fatal error occurred. Program will exit."
  2.  And then you will get run time error on the console,
        java.lang.NoSuchMethodError: main
        Exception in thread "main" 


Why this run time error?
Remember when you run this program, JVM tries to search the 
public static void main(String[] args)
as an entry point in your program. But it doesn't find one. Rather it find's public void main(String args[]) thus is not permitted the gate pass to execute or enter the program and the program exit with run time error.



--------------------------------------------------*-----------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.






You may also like to read about:

No comments:

Post a Comment

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.