Why do String comparisons return true, whereas Double comparisons return false?
String s1 = "a";
String s2 = "a";
System.out.println(s1 == s2); // true
Double d1 = 1D;
Double d2 = 1D;
System.out.println(d1 == d2); // false
I have some thoughts on my mind on the matter, but it is always a pleasure to hear from you first.
String literals are interned – autoboxed doubles aren’t. Other autoboxing can be guaranteed to use cached objects:
Note that this is only guaranteed for values from -128 to 127, but may work for larger values as well. See section 5.1.7 of the JLS for more information.
Note that for strings it really is only because of the interning of String constants:
… whereas for integer boxing, the reuse of the cached values is performed at execution time: