0

I have tried to make a simple code to compare numbers if is equal using Double class. This is my simple code:

BufferedReader bfr= new BufferedReader(new InputStreamReader(System.in));
    Double number1;
    Double number2;
    System.out.println("Ask for first number:");
    number1 = Double.parseDouble(bfr.readLine());
    System.out.println("Ask for second number:");
    number2 =  Double.parseDouble(bfr.readLine());
    
    if(number1==number2) {
        System.out.println("These numbers are equals!");
        System.out.println(number1);
        System.out.println(number2);
    }else {
        System.out.println("They're differents!");
        System.out.println(number1);
        System.out.println(number2);
    }

When I use "int" instead Double and the operator "==" it works fine but when I use "Double" it shows me they are different numbers even the same numbers are entered. I've tried to use Object.equals() method it works fine but I want to know why "Double" class does not admit operator "==".

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
B1rt
  • 1
  • 1

1 Answers1

2

The important difference between int and Double here is not the floating point nature (though that can make computations behave in unexpected ways), but the fact that int is a primitive type and Double is a reference type (a wrapper around double).

When you compare reference type values using == you check for object identity. I.e. the expression number1 == number2 means "do the variables number1 and number2 reference the exact same object", which is almost certainly not what you want.

The solution, as you found is to use number1.equals(number2).

Another workaround would be to switch from Double (the wrapper) to double the primitive type. Usually you can just assign one to the other and the appropriate autoboxing/autounboxing will handle the conversion.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614