Aamir
Aamir

Reputation: 2424

Equality Operator subtle differences

Why does the if conditional evaluate to true in this program? How is 10 equivalent to 10.0?

 public class Test {
     public static void main(String[] args) {
         int i = 10;
         double d = 10.0;

         if (i == d) {
             System.out.println("hi");
         } else {
             System.out.println("bye");
         }
    }
}

Upvotes: 3

Views: 84

Answers (2)

Bruce
Bruce

Reputation: 8849

int will be converted into double when we compare int with double. see this https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.21.1

Upvotes: 3

Tagir Valeev
Tagir Valeev

Reputation: 100199

Because of binary numeric promotion rules described in Java Language Specification, section 5.6.2. These rules apply to the binary operations on numbers of different type. It says that:

If either operand is of type double, the other is converted to double.

Upvotes: 11

Related Questions