I have a question about the following piece of code:
public class Equivalence {
public static void main(String[] args) {
Integer n1 = new Integer(47);
Integer n2 = new Integer(47);
System.out.println(n1 == n2);
System.out.println(n1 != n2);
}
}
The resulting output surprised me:
false
true
I have checked the constructor in Javadoc online, nothing help from there.
Thanks in advance
Thank you
Only primitive types can be reliably compared with
==. For objects (andIntegeris an object type), theequals()method should be used.==can be used for objects but only to check whether two objects are in fact the same. So for example:It’s best if you think of
ints as the number itself andIntegers as a post-it note with the number written on it.==will only return true if you’re talking about the same post-it note,equals()however will return true for any two notes with the same number on it.What complicates the issue is that since version 1.5 Java also has autoboxing, that is,
ints are automatically converted toIntegerand vice versa when required. This can lead to very surprising results if you’re not careful.