Conditional operator (?:) is the only ternary operator available in Java which operates on three operands. The symbol “?” placed between the first and the second operand , and ” : ” is inserted between the second and third operand. The first operand (or expression) must be a boolean . The conditional operator together with operands form a conditional expression which takes the following form.
where expr1 is a boolean expression and expr2 and expr3 are the expressions of any type other than void. The expr2 and expr3 must be of the same type.
If expr1 has value true, the operator returns a result expr2 .
If expr1 has value false, the operator returns a result expr3 .
During the calculates the value of the first argument . if it has the true value , then calculates the second (middle ) argument returned as a result . However , if the calculated result of the first argument is false, then it is given the third ( last ) argument the returned as a result. Here is an example of the use of the operator ” ? ” :
//Program to Find greatest of three numbers using Conditional Operator
import java.util.Scanner; //program uses Scanner class
public class ConditionalOperator
public static void main(String args)
//create Scanner object to obtain input from keyboard
Scanner input=new Scanner(System.in);
System.out.print("Enter the Three Number : "); //prompt for input
a=input.nextInt(); //Read First number
b=input.nextInt(); //Read Second number
c=input.nextInt(); //Read third number
result = (a>b)? ((a>c)?a:c) : ((b>c)?b:c);
System.out.println( result + " is Greatest");