My Practice Tests book contains this question on the ternary operator:
// What is the output of the following application?
public class Transportation {
public static String travel(int distance) {
return(distance < 1000 ? "train" : 10);
}
public static void main(String[] args) {
travel(500);
}
}
It does not compile. The explanation given is the following:
Ternary operations require both right-hand expressions to be of compatible data types. In this example, the first right-hand expression of the outer ternary operation is of type String, while the second right-hand expression is of type int. Since these data types are incompatible, the code does not compile, and Option C is the correct answer.
Is that really the reason? It looks to me like this example doesn't compile because 10 is not a String and a String is what the method must return.
I'm asking because
System.out.println(distance < 1000 ? "train" : 10);
compiles and runs without a problem.
String
'?System.out.println
example proves it. That's the whole point of my question. What each of the two right-hand expressions have to be compatible with is with the return type of the function (which happens to be String in this example). The text book's answer can be interpreted both ways and that why it's ambiguous in my opinion.