The Java Ternary Operator (aka Conditional Operator)
The Java ternary operator, also known as the conditional operator, is a far more condensed version of if/else statements, but somewhat more limiting. It is extremely useful, but gets far too little usage. The basic syntax is as follows:
result = condition ? ifTrue : ifFalse;
Basically, if the condition
is true, result
is set to ifTrue
, if it is false result
is set to ifFalse
. Here is another example:
int result = (5 < 4) ? 1 : 2;
In this case result
would be 2
as 5 < 4
evaluates to false. (The parentheses around the 5 < 4
are optional, I just like to use them for improved readability).
The ternary operator can also be used inline with other code, which comes in handy in this example:
System.out.println(onlineUsers + (onlineUsers > 1 ? "users" : "user"));
As you can see, the ternary operator makes it much easier to add in proper pluralization, something I rarely used to bother with before.
Thank you for reading my tutorial!