Java: Comparing different types of numbers (reference types)

·

1 min read

In preparation for my upcoming OCA (oracle certified associate java programmer) certification I came accross a misunderstanding of the equals method.

If you campare two variables with same value but different reference type then the values are treated as not the same. This is because the Java equals method first checks if the types differ. If that's the case immediately it will return false even if the values are equal.

// no problem with primitives
int num1 = 1;
double num2 = 1.0;

System.out.println(num1 == num2); // true

//  reference types
Long long1 = Long.valueOf(1);
Double double1 = Double.valueOf(1);

System.out.println(long1.equals(double1)); // false