lundi 22 mai 2017

Difference between if-else and conditional-operator [duplicate]

This question already has an answer here:

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.

Aucun commentaire:

Enregistrer un commentaire