GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubts on == given  in B&B Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubts on == given  in B&B" Watch "Doubts on == given  in B&B" New topic
Author

Doubts on == given in B&B

Abhijit Das
Ranch Hand

Joined: Sep 25, 2007
Posts: 156
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


Abhijit Das
SCJP 5.0 | SCWCD 1.5
R van Vliet
Ranch Hand

Joined: Nov 10, 2007
Posts: 144
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

Joined: Nov 20, 2007
Posts: 3
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


The Race is not yet over; Because i have not yet won!!
Luca Romanello
Greenhorn

Joined: May 30, 2002
Posts: 11
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 ]
 
GeeCON Prague 2014
 
subject: Doubts on == given in B&B