Search code examples
javaternary-operator

Use ternary operator for flow control in Java


The ?: (ternary) operator can be used instead of an if-then-else statement for assignment, but can also be used in some way for flow control? For example,

flag ? method1 : method2;

Solution

  • Yes, but:

    1. You have to save the result; you can't just have an expression on its own (in Java; you can in some other languages).

    2. The methods can't have a void return type.

    The type of the conditional expression will depend on the return types of the methods you use. If both return booleans, the type will be boolean; if both are numeric, the result will be numeric; otherwise, the result will be a reference type (e.g., like Object).

    E.g.:

    x = flag ? method1() : method2();
    

    More in JLS §15.25 - Conditional Operator ? :.

    If it were important to you to be able to use the conditional this way (personally, I'd stick with flow control statements), you could define a utility method that looked like this:

    static void consume(Object o) {
    }
    

    And then:

    consume(flag ? method1() : method2());