Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Auto Boxing

 
lalitha kaparapu
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic