Equal and NOT Equal in Integer?

I just discovered one strange and interesting thing. I get confused when first seeing this one.

How about I write this code?

Integer i1 = 1000;
Integer i2 = 1000;

It will return "false". Whenever the Integer is a wrapper class, so it will belongs to different objects.

How about this one?

Integer i3 = 10;
Integer i4 = 10;

It will return "TRUE". Why? Why show two different results, one return false the other return true. But how come, it is same concept!!!


The answer is, in order to save memory, two instances of the following wrapper objects will always be == when their primitive value are the same.

  • Boolean
  • Byte
  • Character from \u0000 to \u007f (7f is 127 in decimal)
  • Short and Integer from -128 to 127.

Yes, I know it, in order to save memory, so it become like that. So why first time I see it I will get confused, is it the book talk wrong thing? Not! I try in my machine, it showed the same result.

If I not see this, if the Sun Exam come out this question, I definite will… So I need to be very very careful about this. Since Java 5 the creator of Java is giving programmer more convenient way to construct code, so it may be some things not following logic, so as a testtaker we need to be very careful about this.

Author: fyhao

Jebsen & Jessen Comms Singapore INTI University College Bsc (Hon) of Computer Science, Coventry University

One thought on “Equal and NOT Equal in Integer?”

  1. 我现在发现Java和C++满相似的,
    有些代号和C++都一样,比如== , != , || , &&

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.