I'm surprised the second case return true
. But that why in Java Puzzlers they advise against mixing the use of Wrapper classes and the ==
operator.
Take a look at this class and code:
public class RichardInt {
private int value;
public RichardInt(int value) {
this.value = value;
}
}
What would be the result of the following?
RichardInt aa = new RichardInt(100);
RichardInt bb = new RichardInt(100);
System.out.println(aa == bb); // prints false
It prints false because the equals operator ==
compares references when used with objects. Remember, in Java, objects are reference types, while primitives (like int
) are value types. (note: can someone let me know if I'm misusing "value type"? I have a feeling I am.) The following would print true:
RichardInt aa = new RichardInt(100);
RichardInt bb = aa;
System.out.println(aa == bb); // prints true
... since aa
and bb
reference the same instance of RichardInt
.
So maybe the above behavior is easier to understand in the following example...
Intger aaa = new Intger(1000);
Intger bbb = new Integer(1000);
System.out.println(aaa == bbb); // prints false
In more recent versions of Java, the wrapper classes (Integer
and Float
and Boolean
etc...) can auto-box, meaning you can do the following:
Integer aa = 1000;
// this is a shorthand for...
// Integer aa = new Integer(1000);
But it leads to confusing behavior when you try things like this:
Integer aaa = 1000;
Integer bbb = 1000;
System.out.println(aaa == bbb); // prints false
Or even better, you can end up with puzzles like this...
// what values of x and y will result in output?
if(!(x<y)&&!(x>y)&&!(x==y)) {
System.out.println("How is this possible?");
}
In the end, whenever dealing with objects, you'll want to use .equals()
instead of ==
.
Integer aaa = 1000;
Integer bbb = 1000;
System.out.println(aaa.equals(bbb)); // prints true