July 17, 2022

Java Ternary Operator With Examples

In the post conditional operators in Java we talked about the Conditional-AND and Conditional-OR operators, here we'll talk about another conditional operator known as ternary operator in Java (?:).

Ternary operator uses three operands thus the name ternary operator and it can be used in place of if-else statement or switch-case statement to make code more compact and readable.

Java ternary operator syntax

Ternary operator in Java has the following form-

result = boolean_expression ? Operand1 : Operand2

First operand is always a boolean expression returning either true or false. If the boolean expression is true then the evaluation of Operand1 is assigned to result, if the expression is false then the evaluation of Operand2 is assigned to result.

Ternary operator Java example

As already said ternary operator can be used in place of if-else statement to make the code more compact.

For example the following if-else statement-

String str;
if(age >= 18){
  str = "You can vote";
}else{
  str = "You can't vote";
}

can be written using ternary operator as follows-

String str = (age >=18) ? "You can vote" : "You can't vote";

Nested ternary operator

Ternary operator in Java can be nested too though it makes it a little less readable.

For example the following if-else statement-

if(i > 500){
  System.out.println("Value more than 500");
}else if(i > 200){
  System.out.println("Value more than 200");
}else{
  System.out.println("Value less than 200");
}

can be written using ternary operator as follows-

String str = (i > 500) ? "Value more than 500" : (i > 200) ? "Value more than 200" : "Value less than 200"; 

That's all for the topic Java Ternary Operator With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment