Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is any difference in Integer Wrapper class and String class using boxing

 
jami siva
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Gugy,

I didn't understand the Autoboxing feauture of this below code

Integer i = new Integer(1000);
int j= 1000;
if (i==j)
{
System.out.println("both are equal for Integer");
}
String s = new String("rsr");
String s1="rsr";
if(s==s1) {
System.out.println("both are equal FOR String");
}




when im trying to run ths code it prints
both are equal for Integer

and below is not printed , this is OK (i know what String Class does)
both are equal for string

but why the above one is printed(both are equal for Integer), Is any specific way to treat in Autoboxing


Thanks


 
Paul Beckett
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try with "Integer j" in place of "int j" and notice the difference in behaviour.

In your code, when comparing the primitive with the wrapper it actually unboxes the wrapper to do a primitive v primitive comparison


 
Rob Spoor
Sheriff
Pie
Posts: 20526
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When a primitive is compared with a wrapper, the wrapper is unboxed. As such, you are comparing the int 1000 with the int 1000.

Try turning i into null and then compare again:
And please, use code tags in the future.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic