Why the main method in java is public static void
What is the "main" method in java??
  • It is the entry point of execution of any java program.
  • We must have a main(String args[]) or main(String ...) method in a class for its execution.
  • We can have multiple main() methods in a class.
Why is main method "public" ??
  • The main method is always marked as public  because it must always be visible or available to the JVM. You can even say that this is the java convention and it needs to be followed.
  • If we make our main() method as private, our code will still compile without giving any compilation error, but at runtime it will throw an exception "Main method not found in class Class, please define the main method"
Why is main method "static" ??
  • A main method is always static, this because whenever a class has to be accessed, first its object is to be created and only then the class can be instantiated. 
  • The static keyword allows the method to be accessed by the class name without instantiating the class.
Suppose we have a class
public class TestClass{
    public TestClass(){
 System.out.println("Hello World Default Constructor");
    }
    public TestClass(String name){
 System.out.println("Hello World Argumented Constructor");
    }
    public static final void main (String args[]){
 System.out.println("Hello World");
    }
}

The above program will give the output "Hello World", because it does not calls the constructors. The JVM would not know what constructor to call and in case of  argumented constructor, what arguments to pass. If the main method was not static then it first call the super constructor of its super class if any, then its own constructors. But the JVM would not know of any super class of this class because this is the starting point of the program, thus the main method is always static.

Why is main method "void" ??
The main method is always void because it does not return any value to any other function. As the execution of the main method is stopped when the program completes its execution.

No comments :

Post a Comment