Hi frds, can there be more than one main() method in a single program. please justify. thanking you :thinking:
The number of main methods can not be greater than number of classes. Each class can have its own main method. But a class can not have more than one main method.
a class can, the jvm looks only for the one that matches the correct format rest it ignores and throw the NoMainMethodFound kinda exception if you try to run it
Code: public class FirstMain { protected void main(){ } public static void main(String[] args) { System.out.println("in first main class"); } } class SecondMain{ private int main(int a){ return a; } protected void main(){ } public static void main(String[] args) { System.out.println("in second main class"); } } class ThirdMain{ protected void main(){ } public static void main(String[] args) { System.out.println("in third main class"); } } Here you are having different mains in different classes. Are you looking for this?
As far I know you can have more than one main method in one java file but not in the same class. There has to be inner classes to have multiple main method.
Yes,there can be more than one main method if method parameters (number (or) type) are different. It’s called overloading. Like:- public static void main(String[] args) public static void main(int args)
Yes,there can be more then one main() method. We just need public static void main(String args[]) to start with and then you can call overloaded main methods inside this main and it should work for sure. eg. Code: public class MultipleMainProgram{ public static void main(String args[]){ main(1); main('c'); main("MyString"); } public static void main(int i){ System.out.println("Inside Overloaded main()"); } public static void main(char i){ System.out.println("Inside Overloaded main()"); } public static void main(String str){ System.out.println("Inside Overloaded main()"); } }
Well, A java program can contain more than one “main” method in a class but, in the terms of Method Overloading. The Standard MAIN method accepts the array of Strings as argument in java. Method Overloading- The feature in java that allows more than one function of same name but different argument and return type.