0

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?

m fauzan abdi
  • 436
  • 5
  • 12
  • 1
    The ternary expression is not doing what you think. Make the two branches your ternary expression to have the same type, and the problem will go away. There are other solutions, but making the types the same is probably the easiest fix. – Tim Biegeleisen Jan 14 '19 at 06:15
  • ah yeah it works.. hmm, I see, so they aren't same – m fauzan abdi Jan 14 '19 at 06:21
  • 1
    From testing, it seems the `new Integer(1)` is being turned into a double. So, you see `1.0`, which looks like a double value, because in fact it is a double. I would have answered, but the duplicate link does a much better job of explaining than I can. – Tim Biegeleisen Jan 14 '19 at 06:23
  • 1
    From java language specification: >ConditionalOrExpression ? Expression : ConditionalExpression > The chosen operand expression is then evaluated and the resulting > value is converted to **the type of the conditional expression** as > determined by the rules stated below. – ZhaoGang Jan 14 '19 at 06:24
  • you could just cast the Integer to an Object and it should also work... – user85421 Jan 14 '19 at 06:24
  • I see, thanks for the help! – m fauzan abdi Jan 14 '19 at 06:24

0 Answers0