dimanche 13 janvier 2019

Different result between normal conditional and ternary operation [duplicate]

This question already has an answer here:

Until now I learned that java provide ternary operator that can replace normal conditional operation.

// normal conditional
result;
if(testCondition){
   result = value1;
} else {
   result = value12;
}

//ternary operator
result = testCondition ? value1 : value2;

but then when I run code below the console prints different result even though has same logic :

public static void main(String[] args) {
    // normal conditional
    Object o1;
    if (true) {
         o1 = new Integer(1);
    } else {
         o1 = new Double(2.0);
    }

    //ternary operator
    Object o2 = true ? new Integer(1) : new Double(2.0);

    System.out.println(o1);
    System.out.println(o2);
}

Output : 
1
1.0

the result surprised me, I always thought normal conditional and ternary are same.
do normal and ternary run different process?,
why does the console prints different result?

Aucun commentaire:

Enregistrer un commentaire