0

I understand the difference between == and .equals. Why the different outcome when using the == operator when it comes to Double and Integer ? Why does JAVA have to treat them differently ?
Double : false

Double value1 = 2.2 ; 
Double value2 = 2.2 ;
System.out.println(value1 == value2 );  // false

Integer: true

Integer num1 = 6 ; 
Integer num2 = 6 ; 
System.out.println(num1 == num2); // true
  • Note that `==` is reference comparison. I guess the `Integer`s are interned (cached), while the `Double`s are not. – kennytm Apr 09 '17 at 15:01
  • you should use `value1.equals(value2)` for check it. – Hadi J Apr 09 '17 at 15:02
  • You are comparing references and not values. Either do: value1.equals(value2); or do: value1.doubleValue() == value2.doubleValue(); – Sachith Wickramaarachchi Apr 09 '17 at 15:04
  • Also see [this thread](http://stackoverflow.com/questions/8561710/why-does-the-double-valueof-javadoc-say-it-caches-values-when-it-doesnt) – RobCo Apr 09 '17 at 15:10
  • 1
    @kennytm The JLS specifies what `Integer` must cache. No need to guess. http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.7 – Lew Bloch Apr 09 '17 at 16:46

0 Answers0