Control Flow

Ternary Operator in Java

The ternary operator is used to execute code based on the result of a binary condition.

It takes in a binary condition as input, which makes it similar to an 'if-else' control flow block. It also, however, returns a value, behaving similar to a method.


Syntax
result = binaryCondition ? valueReturnedIfTrue : valueReturnedIfFalse;

Notes

The ternary cannot be used to execute code. It must be either returned in a method, or set equal to a variable with the same data type as the returned values.


Example
int findMaximum(int a, int b){
    //if a > b, it returns a, if not it returns b
    return (a > b) ? a : b;
}

Add to Slack

< Switch Case   |   For Loop >

© 2019 SyntaxDB. All Rights Reserved.