DEV Community

Cover image for Conditional Expressions
Paul Ngugi
Paul Ngugi

Posted on

Conditional Expressions

A conditional expression evaluates an expression based on a condition.
You might want to assign a value to a variable that is restricted by certain conditions. For example, the following statement assigns 1 to y if x is greater than 0, and -1 to y if x is less than or equal to 0.

if (x > 0)
 y = 1;
else
 y = -1;
Enter fullscreen mode Exit fullscreen mode

Alternatively, as in the following example, you can use a conditional expression to achieve the same result.

y = (x > 0) ? 1 : -1;

Enter fullscreen mode Exit fullscreen mode

Conditional expressions are in a completely different style, with no explicit if in the statement. The syntax is:

boolean-expression ? expression1 : expression2;

Enter fullscreen mode Exit fullscreen mode

The result of this conditional expression is expression1 if boolean-expression is true; otherwise the result is expression2. Suppose you want to assign the larger number of variable num1 and num2 to max. You can simply write a statement using the conditional expression:

max = (num1 > num2) ? num1 : num2;

Enter fullscreen mode Exit fullscreen mode

For another example, the following statement displays the message “num is even” if num is even, and otherwise displays “num is odd.”

System.out.println((num % 2 == 0) ? "num is even" : "num is odd");

Enter fullscreen mode Exit fullscreen mode

As you can see from these examples, conditional expressions enable you to write short and concise code.
The symbols ? and : appear together in a conditional expression. They form a conditional operator and also called a ternary operator because it uses three operands. It is the only ternary operator in Java.

Top comments (0)