The "==" as per me is always reflexive. It should also work both ways otherwise it is not a correct implementation. Should complain about this to Sun
Joined: Dec 16, 2009
Hey I have doubt about left hand side why it's not work but still confuse i have seen in JLS but nothing clearly mention about this
if the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2). If the promoted type of the operands is int or long, then an integer equality test is performed; if the promoted type is float or double, then a floating-point equality test is performed.
Note that binary numeric promotion performs value set conversion (§5.1.13) and unboxing conversion (§5.1.8). Comparison is carried out accurately on floating-point values, no matter what value sets their representing values were drawn from.
public static void main(String  args)
System.out.println(p==n); // incomparable types: java.lang.Number and int
System.out.println(n==p); // box then widen
// Added these lines
Integer q = 4;
System.out.println(q == n); // box
System.out.println(n == q); // unbox
And looking at the boxing rules;
You CANNOT widen from one wrapper type to another (IS-A fails.)
You CANNOT widen then box. (An int can't become a Long.)
You can box and then widen. (An int can become an Integer then a Number.)
I would guess that in the first case, it is trying to unbox Number but there's no primitive type for it to be unboxed to. I don't know why it chooses the Number variable as opposed to the int one other than it is the first thing in the comparisson.
There is this note I found in the SCJP book from Kathey Sierra...
"When == is used to compare a primitive to a wrapper, the wrapper will be unwrapped and the comparison will be primitive to primitive"
This implies to the first case where...
However, in the second case
What I think is... since the first operand to == operator is a reference type... compiler expects to have a reference type as the second argument too, which is not there... so... arrrgghh its really confusing...
The first and the third rule listed here contradict each other.. isn't??
I think they are correct. Take and Integer and a Long. They are both subclasses of Number so you can widen references of either to Number. However you cannot have an int, box to Integer then widen to Long because Integer is not a subclass of Long.
Joined: Feb 17, 2010
ok its fine concept but it should work in both cases why in one case it is working and other case it is showing compiler error....