Autoboxing and Unboxing

Integer i1 = 256;
Integer i2 = 256;
if (i1 == i2) System.out.println("Equal!");
else System.out.println("Not equal!");
The output in this case would be "Not equal!" as these are two separate Integer objects,
so "==" returns false.
However, the following
Integer i1 =100;
Integer i2 = 100;
if (i1 == i2) System.out.println("Equal!");
else System.out.println("Not equal!");
will return "Equal!", Remember that int values from -127 to 127 are in that
range of immutable wrapper types, so the VM actually uses the same
object instance (and therefore memory address) for both i1 and i2. As a
result, == returns a true result.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: