Interview Question – Can we overload main method in java programs, for example in below class Sample, public static void main(String[] args) is given, that is the start point of the program. So, can we write more methods with same name i.e. main (method overloading)?

public class Sample {	

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

Answer:
Yes, we can overload main method in java program. We know that in method overloading the parameters type or number of parameters and return type should be different.

Hence, any method with same name as main () method with different parameters type or number of parameters and return type can be overloaded.

As an example, below class contains multiple overloaded main() methods.

public class ExampleOfMainMethodOverloading {

	// JVM calls this main method with a string array parameter
	public static void main(String[] args) {

		System.out.println("main() called by JVM");

		// We can call overloaded methods here
		main(12);

	}

	// Overloaded main method with Integer parameter
	public static void main(Integer args) {
		System.out.println("Overloaded main() with Integer type parameter");

		// we can also call overloaded method here
		main("hello");

	}

	// Overloaded main method with String type parameter
	public static void main(String str) {
		System.out.println("Overloaded main() with String type parameter");

	}

	// overloaded main() with two string arrays parameter
	public static void main(String[] args, String[] args2) {
		System.out.println("Overloaded main() with 2 String arrays as a parameter");

	}

}

After answering the above question, the next question asked is:

If a class has multiple main() method then how JVM decides which main method to call?

Answer: JVM calls only public static void main(String[] args) method and don’t call any user defined overloaded main method.

NOTE: We cannot override main method because it is static. In fact, in java no static method can be overridden as they are not part of an object of the class.

Related Posts