| Author |
Why varags method called first
|
Tuna Töre
Ranch Hand
Joined: Aug 17, 2008
Posts: 219
|
|
Question is taken from Inquisition John Meyers Mock Exam. class test { public static void main( String args[] ) { new test().method((short)1); } void method(int... i) { System.out.println("int"); } void method(Integer i) { System.out.println("pint"); } void method(byte i) { System.out.println("bite"); } } What is printed ? the answer is int I am asking now that Why int is called first, I know that varags should be called last
|
blog: http://tunatore.wordpress.com
SCJP 6.0 + SCWCD 1.5
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32675
|
|
|
Why do you think? Work out which parameter type you might match.
|
 |
Tuna Töre
Ranch Hand
Joined: Aug 17, 2008
Posts: 219
|
|
Hmmm I can get the idea I thought, We cannot box short to Integer? Am I right ?  [ October 25, 2008: Message edited by: Anut Walidera ]
|
 |
David Pleydell
Greenhorn
Joined: Oct 24, 2008
Posts: 8
|
|
Some Rules from K&B - Primitives widening uses the smallest method argument possible. - You cannot widen from one wrapper to another - You cannot widen and then box - You can box and widen - You can combine var-args with either widening and boxing The only thing that is confusing is the compiler isn't widening to a primitive and then boxing... eg class Eg{ static void test(Long x) {} public static void main(String[] ) { byte b =5; test(b); // widen then box is not allowed } } Why not? If you widen the byte to a long primitive and then box the long to Long what is wrong with that? David
|
 |
Vijay Nimkarde
Ranch Hand
Joined: Oct 16, 2008
Posts: 50
|
|
see hear I explaining at code class test { public static void main( String args[] ) { new test().method((short)1); // hear called by convering short and short is passed } void method(int... i) {// hear method will take argument as 1)int,2)int array 3)int, int,int... 4) subtype of int so on only System.out.println("int"); } void method(Integer i) {// hear method take as arg 1)int or 2)Integer as wrapper object only not other as byte because no automatic widennig and boxing there System.out.println("pint"); } void method(byte i) { // hear takes only 1)byte System.out.println("bite"); } } // imp - as integer and its subtype can implicitly cast to int //if still have probleme just ask question which exactly problem  [ October 25, 2008: Message edited by: Vijay Nimkarde ]
|
Java Developer
|
 |
 |
|
|
subject: Why varags method called first
|
|
|