• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubts on == given in B&B

 
Abhijit Das
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello,

in the chap 3 :Assignment(autoboxing),
the following code having an doubt



class Test
{

public static void main(String [] args)
{
/*
Integer i1 = new Integer(1000);
Integer i2 = new Integer(1000);

Integer i3 = new Integer(10);
Integer i4 = new Integer(10);

*/
Integer i1 = 1000;
Integer i2 = 1000;

Integer i3 = 10;
Integer i4 = 10;

if(i1 == i2 )
System.out.println(" 1000== 1000");
else
System.out.println("1000 != 1000");

if(i3 == i4 )
System.out.println(" 10== 10");
else
System.out.println("10 != 10");

}
}

Commented codes gives different output from the give code. Why, The explanation given in the book is not cleared. Please help
 
R van Vliet
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you be slightly more specific as to what is different, what the intended results should be and what you're getting?
 
Dee-Jay
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When You use ==, it checks if the references point to the same object. Hence it gives false when you check for Integer objects i.e when you use wrapper classes(commented code)

For the uncommented code i think it uses some kind of pool to get the literal values.Hence checking on == gives true.

Can someone clarify on this second part.

Thanks
Dipesh
 
Luca Romanello
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all
The uncommented code produces a different output just for i3 and i4: that's because their literal value is in "byte range" (= between -128 and 127) and the jvm, to save memory, behaves similarly to the String constant pool (= assigning two reference to the same object in heap). This behaviour of Short and Integer is the same for Boolean, Byte and Character (from \u0000 to \u007f), too (I would say, all that is possibly in "byte-or-below range" ).
Hope this helps
Regards
LR

[ November 20, 2007: Message edited by: Luca Romanello ]
[ November 22, 2007: Message edited by: Luca Romanello ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic