So far, you have learned how to use if
else
statements to execute one of two embedded computation-performing
statements. You should also know about Java's
conditional operator,
which
enables you to compute a value from one of two embedded, value-producing
expressions.
The conditional operator sees frequent service in display statements, where it helps you to produce the proper singularplural distinctions. Consider, for example, the following program, which displays a length change:
public class Demonstrate { public static void main (String argv[]) { int change = 1; if (change == 1) { System.out.print("The length has changed by "); System.out.print(change); System.out.println(" minute"); } else { System.out.print("The length has changed by "); System.out.print(change); System.out.println(" minutes"); } } } --- Result --- The length has changed by 1 minute
The program works, but most experienced programmers would be unhappy because there are two separate display statements that are almost identical. Such duplication increases the chance that a bug will creep in during subsequent modification, as you modify one of the duplicates, but overlook another.
You can improve such a program by moving the variationthe part that produces either the word minute or the word minutesinto a value-producing expression inside a single display statement.