| Author |
Comparison of 2 Integer values with "=="
|
craje Shah
Greenhorn
Joined: Feb 20, 2011
Posts: 1
|
|
1.
{
Integer i1=127;
Integer i2=127;
System.out.println(i1==i2);
}
output:true
2.
{
Integer i1=129;
Integer i2=129;
System.out.println(i1==i2);
}
output:false
Why is the output of "1." and "2." different even if the difference is only in the values.
|
 |
Hunter McMillen
Ranch Hand
Joined: Mar 13, 2009
Posts: 490
|
|
When comparing objects like the Integer class, you have to you the equals(Object other) to compare their values. '==' will only compare the references of the objects, not their values.
Hunter
|
"If the facts don't fit the theory, get new facts" --Albert Einstein
|
 |
nitin sethi
Ranch Hand
Joined: Jul 14, 2011
Posts: 59
|
|
You get a difference in output because the operator == behaves differently for Integer/Short objects (created through auto-boxing) initialized with literal values in the range of -128 to +127. This is done to save memory.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
The reason is caching of values between -128 and 127 in combination with autoboxing. If you SearchFirst you'll find a few threads with more detailed explanations.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Wouter Oet
Saloon Keeper
Joined: Oct 25, 2008
Posts: 2700
|
|
|
I like this topic about the same problem.
|
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
|
Actually it says in the Java™ Language Specification that at least the range -128..+127 must be cached. It also says it is preferable for larger ranges to be cached. So the behaviour of == for Integer objects might change from JVM to JVM and might be different next year from this year.
|
 |
 |
|
|
subject: Comparison of 2 Integer values with "=="
|
|
|