Reputation: 5126
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???
Upvotes: 0
Views: 600
Reputation: 220
According to java specification java language specification
If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
Upvotes: 1
Reputation: 136002
These lines
Number l = Integer.parseInt("30");
Number l2 = Integer.parseInt("30");
are converted by Java compiler (auto outboxing) into
Number l = Integer.valueOf(Integer.parseInt("30"));
Number l2 = Integer.valueOf(Integer.parseInt("30"));
Integer.valueOf(int) API says This method will always cache values in the range -128 to 127, inclusive. That is for 30 one the same Integer instance from cache is returned; for 3000 two different (new) instances of Integer are returned.
Upvotes: 1
Reputation: 12398
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);
Upvotes: 2
Reputation: 106400
First, a warning: you're not comparing values; you're comparing memory addresses.
The wrapper classes are still bonafide objects - and the only way to test object equality is to the the equals()
method. If you were comparing against a compatible* primitive, then auto-unboxing would have taken the Integer
into an int
, and did an equality check on that. Note that Number
can't be auto-unboxed; you would have to call intValue()
to get an int
back.
Second, Integer.valueOf()
will cache values in a byte range, from -128 to 127. Any two Integer
objects instantiated within that range will resolve to the same memory address.
*: Either one of those Number
objects would need to become an int
.
Upvotes: 2