by BehindJava

How does ternary operator work in java

Home » java » How does ternary operator work in java

In this tutorial we are going to learn about using ternary operator in Java.

In Java, a ternary operator can be used to replace the if…else statement in certain situations. Before you learn about the ternary operator, make sure you visit Java if…else statement.

Ternary Operator in Java
A ternary operator evaluates the test condition and executes a block of code based on the result of the condition.

Syntax:

result = condition ? trueCase : elseCase;

Here, condition is evaluated and if condition is true, elseCase is executed. And, if condition is false, elseCase is executed. The ternary operator takes 3 operands (condition, expression1, and expression2). Hence, the name ternary operator.

Without using Ternary Operator

public class TernaryOperator {
	public static void main(String[] args) {
		int num = 8;
		String msg = "";
		if (num > 10) {
			msg = "Number is greater than 10";
		} else {
			msg = "Number is less than or equal to 10";
		}
		System.out.println("+++++msg++++++" + msg);
	}
}

Using ternary operator

public class TernaryOperator {
	public static void main(String[] args) {
		int num = 8;
		String msg = num > 10 ? "Number is greater than 10" : "Number is less than or equal to 10";
        System.out.println("+++++msg++++++" + msg);
	}
}

Advantages of Ternary Operator

  • It will shorten the code.
  • It will improve the readability of the code.
  • The code becomes more straightforward.
  • Makes basic if/else logic easier to code.