# 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;
System.out.println(i1==i2);

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

Integer i3 = 10;
Integer i4 = 10;
System.out.println(i3==i4);

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

### Confusing?

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. ALvis says:

我现在发现Java和C++满相似的，
因为我大概看的懂你写的java，
有些代号和C++都一样，比如== , != , || , &&
这些等等~我看C++对你来说应该不是大问题！

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