Ternary Operator Example Java Program

Definition

Operators in Java are similar to those in C++. However, there is no delete operator due to garbage collection mechanisms in Java, and there are no operations on pointers since Java does not support them. At its most basic, the ternary operator (also known as the conditional operator) can be used as an alternative to the Java if/then/else syntax, but it goes beyond that, and can even be used on the right hand side of Java statements.

Syntax

result = testCondition ? value1 : value2

Ternary Operator Example Program

public class TernaryOperator {
	public static void main(String args[]){
		int num1 , num2;
		num1 = 10;
		num2 = (num1 == 1) ? 20: 30;
		System.out.println( "Value of num2 is : " +  num2 );
		num2 = (num1 == 10) ? 20: 30;
		System.out.println( "Value of num2 is : " + num2 );
	}
}

Sample Output

Output is:
Value of num2 is : 30
Value of num2 is : 20