my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Autoboxing with equal method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Autoboxing with equal method" Watch "Autoboxing with equal method" New topic

Autoboxing with equal method

Andry Dub
Ranch Hand

Joined: Nov 06, 2007
Posts: 43
Hi! Please anybody explain me why 1st code produces "equal", but 2nd - "not equal". Where Autoboxing and Autounboxing take place?

Java is my love
ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424
equals() compare values, "==" check refrences.

Auto boxing took place just here: Integer i = 5; int 5 is autoboxed to Integer.
Deepak Jain
Ranch Hand

Joined: Aug 05, 2006
Posts: 637

Try this code and the output will be

The reason is when Integer i = value;
and if the value is between -127 and 128 the value is cached and re-used and hence the result is equal in second case.
However if new Integer(5) is done then JVM will always create a new object no matter the value in the constructor is within the save memory range [-127 to 128]

Fu Dong Jia
Ranch Hand

Joined: May 23, 2007
Posts: 131
go here please explain,may got you clear.

who dare win!<br />SCJP5(94%)|SCWCD5(86%)|SCBCD(100%)|SCEA in progress
Andry Dub
Ranch Hand

Joined: Nov 06, 2007
Posts: 43
Thanks everybody!
I agree. Here's the link:
subject: Autoboxing with equal method
It's not a secret anymore!