*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Auto Boxing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Auto Boxing" Watch "Auto Boxing" New topic
Author

Auto Boxing

lalitha kaparapu
Greenhorn

Joined: Nov 05, 2007
Posts: 16
Hi,
I tried the below code

Integer iObj1 = new Integer(100);
Integer iObj2 = new Integer(100);
if(iObj1 == iObj2)
System.out.println("Objects are equal!");
else
System.out.println("Objects are not equal!");

Predictably, the output is "Objects are not equal!".

Till jdk1.4, two wrapper objects, though both have same value are not considered as equal (==). We had to use the equals() method.

But from JDK1.5, using AUTOBOXING, we can use wrapper objects just like primitive datatypes.

The same piece of code when compiled in jdk1.5 should produce the output as "Objects are equal!".But when I compiled the abouve code with JDK 1.5,I am getting the output as "Objects are not equal!".

Can anyone help me in this regard??
Carlo Leeuwen
Greenhorn

Joined: Nov 07, 2007
Posts: 3
If you do it like this:

if(iObj1.equals(iObj2))

It will compare values and return true,
but == compares object references, which are not the same.

Am I right?
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
Originally posted by lalitha kaparapu:
But from JDK1.5, using AUTOBOXING, we can use wrapper objects just like primitive datatypes.

The same piece of code when compiled in jdk1.5 should produce the output as "Objects are equal!".[/QB]


Hi Lalitha,

Autoboxing only takes effect in expressions where you need a primitive but you only have a wrapper object, or vice versa. However, in the case of (iObj1 == iObj2), you don't need primitives to make the expression valid, so Java simply goes ahead with the usual object reference comparisons. (Remember, one important consideration in the design of Java 1.5 was backward compatibility. The behavior of old programs that use similar Integer object reference comparisons should not change just because you're now running them on a Java 1.5 JVM.)

However, if you change your expression to (iObj1 == (int)iObj2), then autoboxing will kick in--and it'll evaluate to true, as expected.
[ November 07, 2007: Message edited by: Kelvin Lim ]

SCJP 5.0
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Auto Boxing
 
Similar Threads
using == operator on wrapper classes
Can someone help me with this
Some Problem with Wrapper
boxing,==, and equals()
Autoboxing Issue: Integer Wrapper==double primitive