Ternary Operator in Java – The ? : operator

Ternary operator java example with simple program – Ternary operator in java (also known as ? : operator) is a conditional operator and it can be used in place of if-else statement in java programs to write as one liner statement.

Syntax of ternary operator is as ” Condition ? 1st statement : 2nd statement” . “Condition” is the Boolean expression, and if condition is true then 1st statement will be evaluated or else 2nd statement will be evaluated. It is called ternary operator as it takes 3 operands i.e. Condition, 1st statement and 2nd statement.

Below is the simple program example using if else statement and using ternary operator in java program with same output.

Java ternary operator code example :

/*---------------------------------------------
 * IF Else and Ternary operator example code in java
 */

public class ToStringExample {

	public static void main(String[] args) {

		int a = 5, b = 10;
		String result;
		
		/*---------------------------------------------
		 * Using IF then Else example
		 */

		if (a < b) {
			result = " a is less than b";
		} else {
			result = " a is greater than b";
		}
		
		System.out.println("result using if else condition : " + result);
		
		/*---------------------------------------------
		 * Using Ternary operator example
		 */

		result = a < b ? " a is less than b" : " a is greater than b";
		
		System.out.println("result using ternary operator  : " + result);
	}

}

Output:
result using if else condition : a is less than b
result using ternary operator : a is less than b

Related Posts