4

Possible Duplicate:
Can we overload the main method in Java?

When I tryed to compile and run following code, it's working and I see "A" on the console.

Why?

In my mind (String... args) it is the same (String arg, String[] args).

public class AFewMainExample {
    public static void main(String... args) {
        System.out.print("A");
    }

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

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

    public static void main(String arg, String[] args) {
        System.out.print("D");
    }
}
Community
  • 1
  • 1
cane
  • 892
  • 1
  • 10
  • 16

4 Answers4

2

This is actually specified in the JLS, §12.1.4:

The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String. Therefore, either of the following declarations is acceptable:

  • public static void main(String[] args)

  • public static void main(String... args)

There is no difference between the varargs type and the standard array type other than the way in which the function is called, as is noted here. Consequently, the varargs version satisfies all the criteria detailed above and passes as a valid main method. Evidently, all of your other main overloads are not equivalent (otherwise there would be a compile-error).

Community
  • 1
  • 1
arshajii
  • 127,459
  • 24
  • 238
  • 287
1

the first signature is the only one that matches void main (String[] args)

difference fn(String... args) vs fn(String[] args)

Community
  • 1
  • 1
case1352
  • 1,126
  • 1
  • 13
  • 22
0

Parameters (order (or) type (or) both) are different for each of the main method, which leaves only one main method with real main syntax, so no issues.

If you add following main method you will see compile time error, because now there are two methods with exact syntax.

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

Read this tutorial for more info on overloading.

kosa
  • 65,990
  • 13
  • 130
  • 167
0

The main problem was:

+ signature of main(String... args) is different for
    - main(String[] args, String arg)
    - main(String arg, String[] args)

+ main(String... args) 
    - not equals for main(String[] args, String[] args2)
    - only for main(String[] args)

though I catch the compilation error on the following example:

public class MainOverloadingExample4 {

void go(String s){
    System.out.println("void go(String s)");
}
void go(String ... s){
    System.out.println("void go(String ... s)");
}   
void go(String s, String ... arr){
    System.out.println("void go(String s, String ... arr){");
}   
public static void main(String[] args) {
    new MainOverloadingExample4().go("where I am?", "why I am here?");
}
}

The method go(String[]) is ambiguous for the type MainOverloadingExample

cane
  • 892
  • 1
  • 10
  • 16