Hi All,
This is one of the expert level question from the final
test of jwhiz software.
What results from attempting to compile and run the following code?
public class Ternary
{
public static void main(
String args[])
{
int a = 5;
System.out.println("Value is - " + ((a < 5) ? 9.9 : 9));
}
}
Choices are
a.) Value is - 9
a.) Value is - 5
c.) Compile Time Error
d.) None of these
After going throught the complete explanation i got the hidden truth and got convinced that answer would be d. The explanation is as follows:
D is correct. The code compiles successfully. In this code the optional value for the ternary operator, 9.0(a double) and 9(an int) are of different types. The result of a ternary operator must be determined at the compile time, and here the type chosen using the rules of promotion for binary operands, is double. Since the result is a double, the output value is printed in a floating point format. The choice of which value to be printed is made on the basis of the result of the comparison "a < 5" which results in false, hence a takes the second of the two possible values, which is 9, but because the result type is promoted to double, the output value is actually written as 9.0, rather than the more obvious 9, hence D is correct.
Now my question is what will be the affect if i change the type of variable a from int to some other integeral type. Will it have any type in the result.
Pl help.
Thanks
rajat