Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

varargs doubt

pawni jain
Greenhorn
Posts: 22
hello to all,

In following code how it determines to which version of varargs to be called .

public class Eggs {
int doX(Long x, Long y) { return 1; }
int doX(long... x) { return 2; }
int doX(Integer x, Integer y) { return 3; }
int doX(Number n, Number m) { return 4; }

public static void main(String[] args) {
new Eggs().go();
}
void go() {
short s = 7;
System.out.print(doX(s,s) + " ");
System.out.println(doX(7,7));
}
}

output :
4 3

Thanks,
Regards

venu surampudi
Greenhorn
Posts: 16
Here are the rules in descending order of priority for the first call to doX

1. Find an exact match , in our case it first looks for method that has a signature doX(short, short) which it cant find

2. Try to see if it can box the variable and find a match in this case it now looks for doX ( Short, Short ) which it cant find again

3. The next step is to look for a widened version meaning it is looking for something like doX( <Something wider than short>, <Something wider than short > which it does find in

doX(Number,Number) and hence it prints 4.

Since a literal 7 is by default an iteger, here is the priority list of second call

1. Find an exact match , in our case it first looks for method that has a signature doX(int, int) which it cant find

2. Try to see if it can box the variable and find a match in this case it now looks for doX ( Integer, Integer ) which exists and hence

is called to print 3.

Rule of thumb is widen, box, var-args.