Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java Ternary Operators

  • • The operator taking three operands is called ternary operator.
  • • It is also called as conditional operator.
  • • It is represented as exp1? exp2 : exp3;
  • • The mechanism is first the exp1 is evaluated. If the exp1 is true then exp2 will be the output, otherwise exp3 will be the output. Let’s see a program for better understanding.
class ConditionalDemo
{
	public static void main(String[] args)
	{
		int value1 = 1;
		int value2 = 2;
		int result;
		result=(value1>value2) ? value1 : value2 ;
		System.out.println(result);
	}
}

Output

2

Here in above program the expression (value1>value2) is false, so In this example, result will be assigned the value of value2 that is 2. This can be achieved using the if…….else statement as follows :

if(value1>value2)
result=value1;
else
result=value2;

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext