A conditional expression evaluates an expression based on a given condition.
They are used normally to assign a value to a variable that is restricted by a certain condition.
For example if age is greater than 17, then adult otherwise child.
if(age > 17)
{
person="Adult";
}else{
person="Child";
}
You can shorten that using a conditional expression:
person = (age > 17) ? "Adult" : "Child";
How conditional Expressions work
Conditional Expressions simplify one condition if-else statements. They allow you write short and concise code.
They are of the following syntax:
boolean-expression ? expression1 : expression2;
In the above, the result will be expression1
if the boolean-expression
evaluates to true
, otherwise the result becomes expression2
.
In Conditional Expressions, the symbols ?
and :
have to appear together. They are called Conditional Operator.
Conditional Operators are also called Ternary Operator. This is because they use three operands.
Example
Let’s write a simple example determine if items are sorted or not.
import java.util.Scanner;
public class MrConditionalExp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter Ages: ");
int age1 = input.nextInt();
int age2 = input.nextInt();
int age3 = input.nextInt();
System.out.println((age1 < age2 && age2 < age3) ? "Ages are Sorted(ASC)" : "Ages are not Sorted");
}
}
Result 1
Enter Ages:
24
46
55
Ages are Sorted
Result 2
Note we are only considering ascending.
Enter Ages:
65
54
23
Ages are not Sorted
Result 3
Enter Ages:
52
56
51
Ages are not Sorted
Best Regards.