IntelliJ Java IDE
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overloading in Combination with Var-args Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Overloading in Combination with Var-args" Watch "Overloading in Combination with Var-args" New topic
Author

Overloading in Combination with Var-args

kiruthigha rajan
Ranch Hand

Joined: Dec 29, 2011
Posts: 63
Hai can anyone explain me how does the code work??
im unable to understand!!!
thanks in advance

class Vararg {
static void wide_vararg(long... x)
{ System.out.println("long..."); }
static void box_vararg(Integer... x)
{ System.out.println("Integer..."); }
public static void main(String [] args) {
int i = 5;
wide_vararg(i,i); // needs to widen and use var-args
box_vararg(i,i); // needs to box and use var-args
}
}
Dan Drillich
Ranch Hand

Joined: Jul 09, 2001
Posts: 1061
Hi Kiruthigha,

Can you please be more specific about your question?

Regards,
Dan

William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.
ujjawal rohra
Ranch Hand

Joined: Mar 20, 2010
Posts: 90
When calling a method if there is no method matching the exact signature of the called method then the arguments are widened or boxed as required.

The method wide_vararg(long... x) takes a var-arg of type long, that means it can take one or more than one long arguments.
Now when this method is invoked using wide_vararg(i,i) having two ints, then the two ints are matched due to the var-args in the declaration of the method and also the ints are widened and promoted to longs. In this way this method matches the call and is called.

Similarly, when calling box_vararg(i,i), the arguments(two ints) are matched due to var-args declaration and then they are boxed due to an Integer in the declaration.

Hope this helps..

SCJP 6
 
 
subject: Overloading in Combination with Var-args
 
Threads others viewed
widening,boxing and var args??
Doubt on Method Overloading using Var-args
Widening,Boxing and Var-Args Combined
Doubt with compiler error about method matching
varargs and boxing
WebSphere development made easy
without the weight of IBM tools
http://www.myeclipseide.com

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture