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 Wrapper equality 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 "Wrapper equality" Watch "Wrapper equality" New topic

Wrapper equality

Aniket Patil
Ranch Hand

Joined: May 02, 2006
Posts: 218
Accroding to the rules of Wrappers,

Integer i1 = 127;
Integer i2 = 127;

i1 == i2, returns True.

Integer i1 = new Integer(127);
Integer i2 = 127;


Integer i1 = new Integer(127);
Integer i2 = new Integer(127);

i1 == i2, returns False in both cases.

Is this because using new( ) creates a fresh object on the heap, ignoring another object with the same value that might exist on the heap?
[ September 11, 2006: Message edited by: Aniket Patil ]

SCJP 5.0 | SCWCD 1.4 <br /> <br />If you don't know where you are going, any road will take you there!
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
Why does the autoboxing conversion sometimes return the same reference?
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
The API tells you:

public Integer(int value)

Constructs a newly allocated Integer object that represents the specified int value.

value - the value to be represented by the Integer object.

You might like to comare it with valueOf:

public static Integer valueOf(int i)

Returns a Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values.

i - an int value.
a Integer instance representing i.

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi all,

valueOf can be tricky as well:

prints false.
If both parameters were integer literals, it would be true.


all events occur in real time
Meena R. Krishnan
Ranch Hand

Joined: Aug 13, 2006
Posts: 178

print false. How?
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Originally posted by M.R.Krishnan:

print false. How?

Have you checked the API? The caching version of valueOf was recently added in Java 5.0.
I agree. Here's the link:
subject: Wrapper equality
It's not a secret anymore!