Basically, var-args is a an array of argument. For example main(
String... args) is identical to main (String[] args). If you try to overload main (String...args) by main (String[] args), you will get a duplicated method compilation error.
You can pass a String array like this String [] strings = {"1","2"} to this main(String... args) method. Or, you can pass individual strings to the main("1", "2").
Back to your question:
int x = 4; Boolean y = true; short[] sa = {1,2,3};
doStuff(x, y);
doStuff(x);
doStuff(sa, sa);
System.out.println(s);
}
static void doStuff(Object o) { s += "1"; }
static void doStuff(Object... o) { s += "2"; }
static void doStuff(Integer... i) { s += "3"; }
static void doStuff(Long L) { s += "4"; }
1. doStuff(x,y)
The compiler will choose doStuff(Object...o) because x is boxed into Integer and y is boxed into a Boolean when it is declared.
2. doStuff(x)
The compiler has two choices : doStuff(Object o) and doStuff(Integer ...i). But var-args is chosen last. Therefore, the compiler chooses doStuff(Object o) and autobox x into Integer.
3. doStuff(sa, sa)
The compiler has only one choice: doStuff(Object...0). A short[] is an object.
What happens if we change the question like this?
int x = 4; Boolean y = true; short[] sa = {1,2,3};
doStuff(sa, sa);
System.out.println(s);
}
static void doStuff(short[]...s) { s += "1"; }
static void doStuff(Object... o) { s += "2"; }
static void doStuff(Short[]... i) { s += "3"; }
The compiler will choose doStuff(short[] ...s) over doStuff(Object ...o) because it needs to widen the short[] object to Object type.
The compiler will not choose doStuff(Short[] ... i) because short[] cannot be converted into Short[].
What happens if we change the question like this?
int x = 4;
doStuff(x );
System.out.println(s);
}
static void doStuff(Long l) { s += "1"; }
The compiler will have a compilation error because the compiler cannot widen int x into long and box it into Long. For more detail, refer to the K&B, "widening and boxing" section.
What happens if we change the question like this?
int x = 4;
doStuff(x );
System.out.println(s);
}
static void doStuff(Object o) { s += "1"; }
This is an example of boxing and widening. The integer is boxed into an Integer object and widened to an object in order to pass it to doStuff.