aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes varargs doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "varargs doubt" Watch "varargs doubt" New topic
Author

varargs doubt

pawni jain
Greenhorn

Joined: Apr 10, 2008
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

Joined: Jan 03, 2008
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.


If you wanna be cocky you better be kobe !
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: varargs doubt