JAVA ternary operator introduction

The JAVA ternary operator is used to assign a value to a variable based on a Boolean expression.

The JAVA ternary operator (known also as the conditional operator) replaces the “if else” syntax.

The JAVA ternary operator syntax

java ternary operator tutorial for beginners

result = testcondition ? value1: value2;

This means that based on the evaluation of testcondition, one value among value1 or value2 will be assigned to the variable result.

If testcondition is evaluated to true, then value1 will be assigned to the variable result.

Otherwise, value2 will be assigned to the variable result.

So, the JAVA ternary operator is equivalent to this code:

if (testcondition == true) {
result = value1;
}
else {
Result = value2;
}

JAVA ternary operator examples

The calculation of the minimum

minVal = a < b ? a : b;

The calculation of the maximum

maxVal = a > b ? a : b;

Plural and singular

returnString = "There " + (x > 1 ? "are " + x + " trees" : "is one tree") + " in the garden.";

Post a Comment

Previous Post Next Post