That's a Ternary Operator. Check Oracle's doc for further info. Long story short, it is an if-else statement that can be done in a single line and used inside methods and to define variable values.
Syntax:
boolean_expression ? do_if_true : do_if_false;
Parallelism with if-else statement:
if(boolean_expression)
//do_if_true;
else
//do_if_false;
I didn't use brackets on purpose, since you can only execute one line of code in do_if_true
and do_if_false
.
Example of use:
boolean hello = true;
String greetings = hello ? "Hello World!" : "No hello for you...";
This will set someString
as "Hello World!"
since the boolean variable hello
evaluates to true. On the other hand, you can nest this expressions:
boolean hello = true;
boolean world = false;
String greetings = hello ? (world ? "Hello World!" : "Hello Stranger!") : "No hello for you...";
In this case, greetings will have as a value "Hello Stranger!"
;