[java] Can there exist two main methods in a Java program?

Can there exist two main methods in a Java program?

Only by the difference in their arguments like:

public static void main(String[] args)

and second can be

public static void main(StringSecond[] args)

If it is possible, which Method will be used as the entry point? How to identify this?

This question is related to java methods arguments main

The answer is


Yes it is possible to have two main() in the same program. For instance, if I have a class Demo1 as below. Compiling this file will generate Demo1.class file. And once you run this it will run the main() having array of String arguments by default. It won't even sniff at the main() with int argument.

class Demo1 {   
static int a, b;    
public static void main(int args) {
     System.out.println("Using Demo1 class Main with int arg");
     a =30;
     b =40;
     System.out.println("Product is: "+a*b);
 }
public static void main(String[] args) {
      System.out.println("Using Demo1 class Main with string arg");
      a =10;
      b =20;
      System.out.println("Product is: "+a*b);

 }
 }      

Output:
Using Demo1 class Main with string arg
Product is: 200

But if I add another class named Anonym and save the file as Anonym.java. Inside this I call the Demo1 class main()[either int argument or string argument one]. After compiling this Anonym.class file gets generated.

class Demo1 {   
    static int a, b;    
public static void main(int args) {
    System.out.println("Using Demo1 class Main with int arg");
    a =30;
    b =40;
    System.out.println("Product is: "+a*b);
}
public static void main(String[] args) {
    System.out.println("Using Demo1 class Main with string arg");
     a =10;
     b =20;
     System.out.println("Product is: "+a*b);        
} 
}       

class Anonym{
public static void main(String arg[])
{

    Demo1.main(1);
    Demo1.main(null);
}
}


Output:
Using Demo1 class Main with int arg
Product is: 1200
Using Demo1 class Main with string arg
Product is: 200

The below code in file "Locomotive.java" will compile and run successfully, with the execution results showing

2<SPACE>

As mentioned in above post, the overload rules still work for the main method. However, the entry point is the famous psvm (public static void main(String[] args))

public class Locomotive {
    Locomotive() { main("hi");}

    public static void main(String[] args) {
        System.out.print("2 ");
    }

    public static void main(String args) {
        System.out.print("3 " + args);
    }
}

Yes! Any class in Java can have multiple main methods. It's called Overloading (Overloaded methods are methods with same name but with different signatures) but there should only be one main method with parameters like this :- (String[] args) or (String args[])

For example :-public class E {

public static void main(String args){
    System.out.println("Print A");
}
public static void main(String [] args){
    System.out.println("Print B");
}
public static void main(int garbage){
    System.out.println("Print C");
}
public static void main(int i){
    System.out.println("Print D")
}

}

The output of the above program will be "Print B" as only that main method contains the correct method signature identified by the Javac compiler and it compiles that only and leaves the rest.


The answer is Yes, but you should consider the following 3 points.

  1. No two main method parameter should be the same

    Eg.

    • public static void main(int i)
    • public static void main(int i, int j)
    • public static void main(double j)
    • public static void main(String[] args)
  2. Java’s actual main method is the one with (String[] args), So the Actual execution starts from public static void main(String[] args), so the main method with (String[] args) is must in a class unless if it is not a child class.

  3. In order for other main methods to execute you need to call them from inside the (String[] args) main method.

Here is a detailed video about the same: https://www.youtube.com/watch?v=Qlhslsluhg4&feature=youtu.be


Here you can see that there are 2 public static void main (String args[]) in a single file with the name Test.java (specifically didn't use the name of file as either of the 2 classes names) and the 2 classes are with the default access specifier.

class Sum {

    int add(int a, int b) {
        return (a+b);   
    }

    public static void main (String args[]) {
        System.out.println(" using Sum class");
        Sum a = new Sum();
        System.out.println("Sum is :" + a.add(5, 10));
    }

    public static void main (int i) {
        System.out.println(" Using Sum class main function with integer argument");
        Sum a = new Sum();
        System.out.println("Sum is :" + a.add(20, 10));
    }
}

class DefClass {

    public static void main (String args[]) {
        System.out.println(" using DefClass");
        Sum a = new Sum();
        System.out.println("Sum is :" + a.add(5, 10));
        Sum.main(null);
        Sum.main(1);
    }
}

When we compile the code Test.java it will generate 2 .class files (viz Sum.class and DefClass.class) and if we run Test.java we cannot run it as it won't find any main class with the name Test. Instead if we do java Sum or java DefClass both will give different outputs using different main(). To use the main method of Sum class we can use the class name Sum.main(null) or Sum.main(1)//Passing integer value in the DefClass main().

In a class scope we can have only one public static void main (String args[]) per class since a static method of a class belongs to a class and not to its objects and is called using its class name. Even if we create multiple objects and call the same static methods using them then the instance of the static method to which these call will refer will be the same.

We can also do the overloading of the main method by passing different set of arguments in the main. The Similar example is provided in the above code but by default the control flow will start with the public static void main (String args[]) of the class file which we have invoked using java classname. To invoke the main method with other set of arguments we have to explicitly call it from other classes.


the possibility of two main(String[] args) methods within the same scope create confusion for the JVM. It fails to use them as overloaded methods. So the signatures in terms of parameters) must be different.


There can be more than one main method in a single program. Others are Overloaded method. This overloaded method works fine under a single main method

public class MainMultiple{

   public static void main(String args[]){
       main(122);
       main('f');
       main("hello java");
   }

   public static void main(int i){
       System.out.println("Overloaded main()"+i);
   }

   public static void main(char i){
       System.out.println("Overloaded main()"+i);
   }

   public static void main(String str){
       System.out.println("Overloaded main()"+str);
   }
}

There can be more than one main method in a single program. But JVM will always calls String[] argument main() method. Other method's will act as a Overloaded method. These overloaded method's we have to call explicitly.


That would be compilable code, as long as StringSecond was a class. However, if by "main method" you mean a second entry point into the program, then the answer to your question is still no. Only the first option (public static void main(String[] args)) can be the entry point into your program.

Note, however, that if you were to place a second main(String[]) method in a different class (but in the same project) you could have multiple possible entry points into the project which you could then choose from. But this cannot conflict with the principles of overriding or overloading.

Also note that one source of confusion in this area, especially for introductory programmers, is that public static void main(String[] args) and public static void main(String ... args) are both used as entry points and are treated as having the same method signature.


The answer is no; there can only one "main" method - where "main" means an entry point you can "run".

You can code overloaded versions as in your example, but they can't be "run".


The signature of main method must be

public static void main(String[] args) 
  • The parameter's name can be any valid name
  • The positions of static and public keywords can be interchanged
  • The String array can use also the varargs syntax

A class can define multiple methods with the name main. The signature of these methods does not match the signature of the main method. These other methods with different signatures are not considered the "main" method.


In Java, you can have just one public static void main(String[] args) per class. Which mean, if your program has multiple classes, each class can have public static void main(String[] args). See JLS for details.


enter image description here

Case :1 > We have two main method but with "Main" AND "main2" so jvm only a=calling "main" method .

2> Same method but diff params, still jvm calling "main(String[] args) " meyhod.

3> Exactly same method but it gives copile time error as you can not have two same name method in a single class !!!

Hope it will give you clear pic


Only public static void main(String[] args) counts. This is the only signature considered to be the true main() (as the program entry point, I mean).


i have check in java version 1.6.0_32 multiple main method is working but there should one main method like public static void main(String []args) of type signature. Ex is here which i had tested.

public class mainoverload
{
public static void main(String a)
{
    System.out.println("\nIts "+a);
}
public static void main(String args[])
{
    System.out.println("\nIts public static void main\n");
    mainoverload.main("Ankit");
    mainoverload.main(15,23);
    mainoverload.main(15);
}
public static void main(int a)
{
    System.out.println("\nIts "+a);
}
public static void main(int a,int b)
{
    System.out.println("\nIts "+a+" "+b);
}
}    

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to methods

String method cannot be found in a main class method Calling another method java GUI ReactJS - Call One Component Method From Another Component multiple conditions for JavaScript .includes() method java, get set methods includes() not working in all browsers Python safe method to get value of nested dictionary Calling one method from another within same class in Python TypeError: method() takes 1 positional argument but 2 were given Android ListView with onClick items

Examples related to arguments

docker build with --build-arg with multiple arguments ARG or ENV, which one to use in this case? How to have multiple conditions for one if statement in python Gradle task - pass arguments to Java application Angularjs - Pass argument to directive TypeError: method() takes 1 positional argument but 2 were given Best way to check function arguments? "Actual or formal argument lists differs in length" Python: Passing variables between functions Print multiple arguments in Python

Examples related to main

String method cannot be found in a main class method How to access global variables Maven Error: Could not find or load main class Eclipse error "Could not find or load main class" Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args) What does "Could not find or load main class" mean? C# importing class into another class doesn't work In Python, can I call the main() of an imported module? Can there exist two main methods in a Java program? Could not find or load main class with a Jar File