File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Boxing & unboxing 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 "Boxing & unboxing" Watch "Boxing & unboxing" New topic

Boxing & unboxing

sakthi karthik

Joined: Apr 19, 2008
Posts: 28
i cant understand the following expalanation. can anyone please explain this

Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2) System.out.println("different objects");
if(i1.equals(i2)) System.out.println("meaningfully equal");

Produces the output:
different objects
meaningfully equal

Integer i3 = 10;
Integer i4 = 10;
if(i3 == i4) System.out.println("same object");
if(i3.equals(i4)) System.out.println("meaningfully equal");

This example produces the output:
same object
meaningfully equal

The equals() method seems to be working, but what happened with ==
and != ? Why is != telling us that i1 and i2 are different objects, when == is saying
that i3 and i4 are the same object? In order to save memory, two instances of the
following wrapper objects will always be == when their primitive values are the same:
Character from \u0000 to \u007f (7f is 127 in decimal)
Short and Integer from -128 to 127
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
You already posted the key to the answer:
Short and Integer from -128 to 127

Does 10 fall into this range? How about 1000?
sakthi karthik

Joined: Apr 19, 2008
Posts: 28
now i understand , thank you
vinal sen
Ranch Hand

Joined: Dec 13, 2007
Posts: 37
But Karthik,

do remember

produces "not equal".
I agree. Here's the link:
subject: Boxing & unboxing
It's not a secret anymore!