• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

varargs and boxing

 
Guru dhaasan
Ranch Hand
Posts: 126
Java Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in the following code:

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 at[]){
int i=5;
wide_varArg(5,5);
box_varArg(i,i);
}
}


the compilation fails with the following message
varArg.java:7: wide_varArg(java.lang.Long...) in varArg cannot be applied to (int,int)
wide_varArg(5,5);
^
1 error



What is the error here ???
 
Nik Arora
Ranch Hand
Posts: 652
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
the compilation fails with the following message
varArg.java:7: wide_varArg(java.lang.Long...) in varArg cannot be applied to (int,int)
wide_varArg(5,5);

wide_varArg method takes Long wrapper type.When you call method like
wide_varArg(5,5) it will be boxed to Integer wrapper type and compiler will try to widen it into Long wrapper type here the error will get generated because Wrapper type of one cannot be widen to another wrapper type.


Regards
Nik
 
dhwani mathur
Ranch Hand
Posts: 621
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well!!below shown is the link which has two topics you refer to the first topic.

1)Using the Varargs Language Feature

It consist of the same problem as explained by you as well as the explanation for it but you will have to read it completly.
So here is the link.

http://java.sun.com/developer/JDCTechTips/2005/tt0104.html

i hope it helps you.
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

primitive will be boxed to corresponding wrapper and then widening is done.
Integer can't widen to Long. As Nikhil said one wrapper can't widen from
one to another.

Integer can widen to Number or Object but not to any wrapper.


Thanks,
 
Guru dhaasan
Ranch Hand
Posts: 126
Java Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Nik
 
Guru dhaasan
Ranch Hand
Posts: 126
Java Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Chandra
 
Guru dhaasan
Ranch Hand
Posts: 126
Java Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks dhwani

The link was wonderful
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic