13

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.

5
  • 1
    This is quite interesting too: stackoverflow.com/questions/8002603/… Jun 3, 2018 at 18:08
  • 1
    What exactly do you think the difference is between 'incompatible data types' and '10 is not a String'?
    – user207421
    Jun 4, 2018 at 7:49
  • @EJP Put like that there's no difference. The problem is that the text book answer is open for the following interpretation: "The first right-hand expression must be compatible with the second and the second must be compatible with the first."
    – mgr326639
    Jun 4, 2018 at 8:48
  • @mgr326639 What other way is there to put it? The types have to be compatible with each other. They aren't. Your 'following interpretation' says exactly the same thing.
    – user207421
    Jun 4, 2018 at 23:39
  • "The types have to be compatible with each other". No they don't, and my 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.
    – mgr326639
    Jun 5, 2018 at 8:34

3 Answers 3

14

Your method declares that the return type is String. Any return statement must produce an expression that is compatible with the declared return type.

In this case, however, the return type can be int, which explains why the compiler rejects it.

This is not specific to the ternary operator, it can be reproduced with an equivalent if/else block as well:

if(distance < 1000)
   return "train"; //This part is valid
else
    return 10; //This line will be rejected by the compiler

For the same reason, the last line will fail to compile. This is simply because of basic type checking.

System.out.println(distance < 1000 ? "train" : 10); compiles and runs without a problem.

This is because the compiler detects a common type for both String and int, which is Object, and resolves to choose this signature:

java.io.PrintStream#println(Object x) // available in the target class

This, however, isn't applicable to the method return type.

If you changed your return type to Object, your code would compile too. But that's of course not what you're trying to do.

Ternary operations require both right-hand expressions to be of compatible data types

-> This part is in fact valid. here's a way to interpret it: each of the two expressions must be individually compatible:

String value = distance > 1000 ?
                 "train" //this must be compatible with String
                 :
                 10 //this too must be compatible with String (it isn't)

In contrast:

Object value = distance > 1000 ?
                 "train" //this must be compatible with Object (it is)
                 :
                 10 //this too must be compatible with Object (it is)

In other words, the call to System.out.println(distance < 1000 ? "train" : 10) is similar to the last example above, where the expected type is compatible with both expressions.

4
  • 1
    "This is because the compiler detects a common type for both String and int, which is Object" is the reason the original textbook statement "both right-hand expressions to be of compatible data types" is meaningless since everything (at least after boxing) is a Object in the end, so everything is "compatible".
    – luk2302
    Jun 3, 2018 at 18:14
  • @luk2302 That is in fact right. But that statement from the book may need to be rephrased a little when it comes to method signature resolution (the println call), but the idea is similar. I've edited the answer with a little more info to illustrate what the difference is.
    – ernest_k
    Jun 3, 2018 at 18:22
  • 1
    Not that int is only compatible with Object through boxing to Integer.
    – jpmc26
    Jun 3, 2018 at 20:20
  • This part is in fact valid. here's a way to interpret it:... I don't think a statement is valid if the truth can be deduced, but only if interpreted it in the right way. I considered the ambiguity when I first read the text book answer but discarded it when I reached the part Since these data types are incompatible. Notice the plural form. My reasoning was: since String is not incompatible they can't possibly mean "individually". So what they must mean is "amongst each other". Do you agree that the wording of the text book answer could be improved to make is less ambiguous?
    – mgr326639
    Jun 4, 2018 at 8:03
5

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

Both your reasoning and the answer of the author are right.
I think that the right answer to your question is the union of them.

1) the Ternary operator is invalid

because

2) in the current context, the type that you assigned it to : an int cannot be assigned to a String.

You can check it with the error messages emitted by the compiler.

Here, you have to consider that :

return(distance < 1000 ? "train" : 10);

as two things to evaluate by the compiler :

1) distance < 1000 ? "train" : 10 // produces a result

2) returns (the produced result); // return the result that should be assignable to a String according to the method return type

Actually, the compilation error :

Transportation.java:3: error: incompatible types: bad type in conditional expression return(distance < 1000 ? "train" : 10);
int cannot be converted to String

refers the both errors : the error in the conditional expression and its cause : the error of the incompatibility between int and String.

So the compilation error that refers only the incompatibility between int and String in the return will occur only if the ternary is valid at compile time.

Write a valid ternary expression and you could see that the compiler will signal only the error about the return statement :

public static String travel(int distance) {
    return(distance < 1000 ? 15 : 10);
}

error: incompatible types: int cannot be converted to String

0

You are right, the explanation is confusing as different compatible types can be used for the right hand expressions.

You can find a table of the resulting type of the conditional expression according to the types of the second and third operand here.

There can be some type casting with numeric types, as explained in this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.