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 Equality Problem 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 "Equality Problem" Watch "Equality Problem" New topic

Equality Problem

Ramesh Sahu
Ranch Hand

Joined: Jul 14, 2008
Posts: 32
class test {
public static void main(String[] args) {
test inst_test = new test();
int i1 = 2000;
int i2 = 2000;
int i3 = 2;
int i4 = 2;
Integer Ithree = new Integer(2); // 1
Integer Ifour = new Integer(2); // 2
System.out.println( Ithree == Ifour );
inst_test.method( i3 , i4 );
inst_test.method( i1 , i2 );
public void method( Integer i , Integer eye ) {
System.out.println(i == eye );

The output comes out to be :

Can anyone please explain the result & the concept behind it ??
Paul Beckett
Ranch Hand

Joined: Jun 14, 2008
Posts: 96
the == checks to see if both references are for the same object.

iThree and iFour are different objects so the result is false. That should be fairly easy to understand (notice the use of "new" when creating the objects).

When an int is boxed into an Integer as is happening when you call "method" then if the int is between -128 and 127 inclusive then the jvm uses a cache. So all boxed references of the same int in that range will refer to the same object.

All the tests will be true if you use .equals() instead of ==.

[ July 29, 2008: Message edited by: Paul Beckett ]
[ July 29, 2008: Message edited by: Paul Beckett ]
Sandeep Bhandari
Ranch Hand

Joined: Apr 16, 2004
Posts: 201
Please note that this will result in compiler error in case of jdk1.4

its autoboxing of jdk1.5 which makes this code work.

SCJP 96% | SCWCD 90%| SCJP mock exams | My SCJP blog
It is sorta covered in the JavaRanch Style Guide.
subject: Equality Problem
It's not a secret anymore!