Java Language Basic Control Structures Ternary Operator


Sometimes you have to check for a condition and set the value of a variable.

For ex.

String name;

if (A > B) {
    name = "Billy";
} else {
    name = "Jimmy";

This can be easily written in one line as

String name = A > B ? "Billy" : "Jimmy";

The value of the variable is set to the value immediately after the condition, if the condition is true. If the condition is false, the second value will be given to the variable.