Ternary Operator is the
short hand of the if-else
block, where a condition is evaluated to true or false and following statement is executed.
Syntax of the ternary operator is below
<boolean expression> ? <executed when condition is true> : <executed when condition is false>
A typical example of if-else block is shown below where we check if a variable is null or not.
String s = "hello" if( s != null ) println s else println "not found"
We can replace the above code with the
ternary operator as shown below
String s = "hello" println s !=null ? s : "not found"
Here, the variable
s is assigned a string
hello and condition
evaluates to true hence the statement after
? is executed which returns
Elvis operator is the short hand of the
Ternary operator explained
above. In this operator we
do not specify the true condition. The true condition is will evauate to
the expression itself.
Syntax of the
elvis operator is
<expression> ?: <executed when condition is false>
Let's see an example
String s = "hello" println s!=null ?: "not found" // true println s ?: "not found" // hello println null ?: "not found"
In the above example,