Home Segments Top Top Previous Next

395: Mainline

So far, you have learned how to use ifelse 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 singular–plural 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 variation—the part that produces either the word minute or the word minutes—into a value-producing expression inside a single display statement.