why not to use == when comparing primitive wrapper classes like Long,Integer etc.why they don't work.
public static void main(String[] args) {
Number l = Integer.parseInt("30");
Number l2 = Integer.parseInt("30");
System.out.println(l == l2);
l = Integer.parseInt("3000");
l2 = Integer.parseInt("3000");
System.out.println(l == l2);
}
why in the above code one result in true and other false???
Consider this case:
new Integer(30)==new Integer(30)
On each side of ==
you have a new instance, then the left hand side and the right hand side are different objects, and the comparison evaluates as false (as it tests instance identity).
The case with boxing is more complicate, as it relies on Integer.valueOf
, which already caches the value for some low-value integers (at least in the range -128 to 127, though implementations can choose a greater range).
This issue is similar to the following, where the equality evaluates as true
even when we have been told that we should compare strings using equals
.
String a = "foo";
String b = "foo";
System.out.println(a==b);