Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why varags method called first

 
Tuna Töre
Ranch Hand
Posts: 220
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Campbell Ritchie
Sheriff
Pie
Posts: 49466
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you think? Work out which parameter type you might match.
 
Tuna Töre
Ranch Hand
Posts: 220
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic