Ternary Operator

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
  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 s!=null evaluates to true hence the statement after ? is executed which returns s itself.

Elvis Operator

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,

  1. Expression s!=null evaluates to true, and will print true
  2. Expression s in will evaluate to true according to Groovy Truth, and will return hello, the value of variable s
  3. Expression null will evaluate to false according to Groovy Truth and will return not found string