How to Use a Conditional Operator in Java
Java has a neat feature. Using this feature, you can think about alternatives in a very natural way. And what does in “a natural way” mean? Think about this while you’re programming:
//The thinking in Listing 11-3: What should I do next? If this is a leap year, I_ll make the numberOfDays be 29; Otherwise, I_ll make the numberOfDays be 28.
This example shows the programmer wandering into an if statement without a clue about what to do next. That seems silly. It’s February, and everybody knows what you do in February. You ask how many days the month has.
This doesn’t reflect the most natural way to think about February. So here’s a more natural way:
//A more natural way to think about the problem: The value of numberOfDays is... Wait! Is this a leap year? If yes, 29 If no, 28
In this second, more natural way of thinking, you know from the start that you’re picking a number of days. So by the time you reach a fork in the road (Is this a leap year?), the only remaining task is to choose between 29 and 28.
Make the choice with finesse:
case 2: System.out.print("Leap year (true/false)? "); isLeapYear = keyboard.nextBoolean(); numberOfDays = isLeapYear ? 29 : 28;
The ? : combination is called a conditional operator. This is how the natural thinking about February can morph into the conditional operator’s format.
Taken as a whole, isLeapYear ? 29 : 28 is an expression with a value. And what value does this expression have? Well, the value of isLeapYear ? 29 : 28 is either 29 or 28. It depends on whether isLeapYear is or isn’t true. That’s how the conditional operator works:
If the stuff before the question mark is true, the whole expression’s value is whatever comes between the question mark and the colon.
If the stuff before the question mark is false, the whole expression’s value is whatever comes after the colon.
So the conditional operator’s overall effect is as though the computer is executing
numberOfDays = 29;
numberOfDays = 28;
One way or another, numberOfDays gets a value, and the code solves the problem with style.