2

I have come across the following code snippet and need help in understanding what's going on under the hood.

    Object o1,o2;

    o1 = true?new Integer(2):new Double(3);
    if(true){
        o2 = new Integer(2);
    }else{
        o2 = new Double(3);
    }

    System.out.println(o1 + "\t" + o1.getClass().getName());
    System.out.println(o2 + "\t" + o2.getClass().getName());

The above code would seem to be easy enough to guess the accurate result, but when I run it, I get the following output.

2.0     java.lang.Double
2       java.lang.Integer

It looks like the JVM is somehow typecasting the output (Integer) to a Double in the first case and not in the second.

I would like to know the reason behind this, as I have always believed that the conditional-operator and the if-else statements are equivalent.

Adit A. Pillai
  • 647
  • 1
  • 10
  • 22

0 Answers0