Java Language Basic Control Structures Ternary Operator

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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.



Got any Java Language Question?