Why Java main method is static? – Best Explanation

Why Java main method is static and public is a frequently asked interview question generally asked to freshers candidate. To answer why java main method is static, it is good to know the concept of static method and instance method in Java. However, it is briefly written in the answer.

Answer: Java main method is static, so that compiler can call it without creation of object or before creation of an object of the class. Look at the below java program example, main () method is declared public static void in a class called Test.

public class Test {
	
	public static void main(String[] args) {
		

	}
}

We know that main () method in Java program is the starting point from where compiler starts program execution. So, compiler needs to call main () method first in any java application or program.

We also know the java programming concept that to call an instance method () of a class, first we need to create the object of the class and then can call instance method using class object created in the program. Static member method of a class can be called by using class name only without creating an object of a class.

Let say if main () method is not static in the class then how compiler will call the main () method? To call the main method, compiler need to crate an object of the class. But, it cannot create the object of the class because it has to enter main () first.

That’s the reason java main () method is static, so, compiler can call it without creating any object of the class Test.

Java program example of a static method call :

class Book{

	//Static method
	public static void GetBookInfo(){
		System.out.println("Book Info");
	}
}

public class Test {
	
	public static void main(String[] args) {
		
		//Call static method of Book class using
		//class name only
		Book.GetBookInfo();

	}

}

Why main method is public in java?

Java main () method is public, so that it can be accessible from outside of the class. Public keyword is access specifier that controls the accessibility of class data members and member methods() in Java programs.

Related Posts