Ternary operator | Java

Ternary operator | Java

Basics • Java Fundamentals

  • Represented by ?:

  • Operator have more than three operand are called ternary operators.

  • The only possible ternary operator in Java is conditional operator.

Syntax:

expression ? true : false

If expression is true then result is will be true otherwise false.

Example -

int x = (10 < 20) ? 30 : 40;
System.out.println(x); // 30

We can perform nesting of conditional operator also.

int x = (10 > 20) ? 30 : ((40 > 30) ? 70 : 60);
System.out.println(x); // 70

Conclusion

The ternary operator in Java offers a concise way to express conditional statements. Mastering its usage enhances code readability and simplifies decision-making, contributing to efficient and expressive programming.