4

I have two overloaded methods with varargs int and long. When I run a test passing integer it seems to prefer the varargs long method. Whereas, if I make the methods static and run with an integer it seems to prefer the varargs int method. What's going on here?

void varargs(int... i){

    System.out.println("Inside int varargs");
    for(int x : i)
        System.out.println(x);
}

void varagrs(long... l){

    System.out.println("Inside long varargs");
    for(long x : l)
        System.out.println(x);
}

static void staticvarargs(int...i)
{
    System.out.println("Inside static int varargs");
    for(int x : i)
        System.out.println(x);
}

static void staticvarargs(long...l)
{
    System.out.println("Inside static long varargs");
    for(long x : l)
        System.out.println(x);
}

public static void main(String args[]){
    VarArgs va = new VarArgs();
    va.varagrs(1);
    staticvarargs(1);
}

Output:

Inside long varargs 1

Inside static int varargs 1

EDIT: I should've chosen better method names. There was a typo varargs, varagrs. Thanks zhong.j.yu for pointing that out.

Corrected code and expected behavior:

void varargs(int... i){

    System.out.println("Inside int varargs");
    for(int x : i)
        System.out.println(x);
}

void varargs(long... l){

    System.out.println("Inside long varargs");
    for(long x : l)
        System.out.println(x);
}

static void staticvarargs(int...i)
{
    System.out.println("Inside static int varargs");
    for(int x : i)
        System.out.println(x);
}

static void staticvarargs(long...l)
{
    System.out.println("Inside static long varargs");
    for(long x : l)
        System.out.println(x);
}

public static void main(String args[]){
    VarArgs va = new VarArgs();
    va.varargs(1);
    staticvarargs(1);
}

Output:

Inside int varargs 1

Inside static int varargs 1

The_301
  • 851
  • 1
  • 8
  • 13

1 Answers1

3

It's a typo

void varagrs(long... l){
         ^^ 

That's why it's nice to have an IDE with spell checking (e.g. IntelliJ)

After fixing the typo, the compiler chooses (int...) over (long...) because int is a subtype of long (4.10.1), so the 1st method is more specific (15.12.2.5). Note though int[] is not a subtype of long[] (4.10.3).

ZhongYu
  • 19,446
  • 5
  • 33
  • 61