Using the Conditional Operator

The conditional operator is the only ternary operator in Java. It is used to replace certain types of if-then-else statements. You will learn more about if statements later in the book.

The conditional operator is represented by a question mark (?). It can seem somewhat confusing at first, but the conditional operator can be used very effectively once understood.

The conditional operator has the following general form.

expression1 ? expression2 : expression3

Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated.

The result of the conditional operator is that of the expression evaluated. Both expression2 and expression3 are required to return the same type.

In Java, you cannot use 0 as denominator in integer division.

Here, is an example which prevents division by 0 using the conditional operator.

result = (denominator == 0) ? 0 : numerator / denominator;

When Java evaluates this assignment expression, it first evaluates the expression in the parenthesis, which is not really necessary. In other words, the expression to the left of the question mark is first evaluated. If the denominator equals to zero, then the expression between the question mark and the colon is evaluated and used as the value of the entire conditional expression. If denominator is not equal to zero, then the expression after the colon is evaluated and used for the value of the entire conditional expression. The result produced by the conditional operator is then assigned to result.

Here is a program that demonstrates the conditional operator. It uses it to obtain the absolute value of a variable.

class ConditionalOperatorDemo {

	public static void main(String ... arguments) {
		int i = 10;
		int k = i < 0? -i : i;
		
		System.out.print("Absolute value of i is " + k);

		i = -7;
		k = i < 0 ? -i : i;
		System.out.print("Absolute value of i is " + k);
	}
}

The output generated by the program is shown here.

Absolute value of 10 is 10
Absolute value of -7 is 7