by Dinesh Thakur Category: Operators and Expressions

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.

expr1? expr2:expr3

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)
          int a,b,c,result;
          //create Scanner object to obtain input from keyboard
          Scanner input=new Scanner(;
          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");

Conditional Operator in Java with Example

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.