vijay kaaman wrote:
2. I can do this
int x = 1;
Number y = x;
but when I do this..
if (y == x) I get an error..
would it be safe for me to assume that, a Number object and a Integer object cannot be compared, even if Integer is ONLY a subclass of Number. I ask this question becuase the compiler does not complain when I try to do this.
First of all, youre not comparing an Integer object with a Number object. You're comparing an int primitive with a Number object.
Secondly, you're using identity
test, this is a little tricky when what you really want to check for is equality, since youre actually comparing the identity of the objects and not their value.
vijay kaaman wrote:
int x = 1;
Integer y = x;
if (y == x)..no errors
What happens here, is that you are comparing an Integer object with an int, which leads to the Integer being unboxed before the comparison is made, which is why you do not get an error. In your previous example, your Number object was in fact an Integer object that had been converted to a Number due to your assignment. However in that case, the JVM does not know it is an Integer since you stored it in a Number reference, so it cannot be unboxed in order to be compared.
I'd recommend reading up on wrappers in general, and also on the equality and identity tests (.equals() and '==').
// Andreas