Ternary Operator

This operator is a shorthand version of the if/else construct that some developers find confusing, and others like. It takes the following form:

boolean expression ? action if true : action if false

The first part is an expression that evaluates to either true or false. The code after the question mark executes if the expression is true; the code after the colon executes only if the expression is false.

It serves as a replacement shorthand for the following construct:

if (boolean expression) {
   action if true;
} else {
   action if false;

So it looks like this in code:

public int returnLesserOfTwo(int x, int y) {
   return (x < y ? x : y);

If you pass that method an x value of -20 and a y value of -80, it returns -80. I like ...

Get Java Garage now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.