I've discovered today that I do not actually understand how the ternary operator works. Have a look at the following sample code:
Integer intValue = 5;
Double doubleValue = 6.0;
boolean useDouble = false;
// Using Ternary
Number num = (useDouble) ? doubleValue : intValue;
System.out.println(num + "\t" + (num instanceof Integer)); // 5.0 false
// Using If-then-else
if (useDouble) {
num = doubleValue;
} else {
num = intValue;
}
System.out.println(num + "\t" + (num instanceof Integer)); // 5 true
I had thought that both cases would give me an instance of Integer... but that is not the case. I'd be grateful if someone could explain the details of why ternary and if/else behave differently.
Thanks!