Home > Java > Why Integer Object will behave like this?

Why Integer Object will behave like this?


Integer i1 = 127;

Integer i2 = 127;

System.out.println(i1==i2);

System.out.println(i1.equals(i2));

Integer i1 = 128;

Integer i2 = 128;

System.out.println(i1==i2);

System.out.println(i1.equals(i2));

O/P

true , true,  false ,true

Have you wondered by seeing the output, it should be false, true, false, true right?

But if you run the code it gives the out put as true, true, false, true.

why because Integer object have cache values between -128 to 127.

So first it will be true in the case of 127 as it is in the range of cached values.

But latter case if false as 128 wont fall under the cached values.

http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#valueOf%28int%29

Advertisements
Categories: Java
  1. No comments yet.
  1. No trackbacks yet.

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: