O'Reilly logo

Java Garage by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required