When Should You Use Break Statements in Your Java Programming? - dummies

When Should You Use Break Statements in Your Java Programming?

By Barry Burd

At one time or another, every Java programmer forgets to use break statements. At first, the resulting output is confusing, but then the programmer remembers fall-through. The term fall-through describes what happens when you end a case without a break statement.

What happens is that execution of the code falls right through to the next case in line. Execution keeps falling through until you eventually reach a break statement or the end of the entire switch statement.

Just check out this code. This code has a switch statement gone bad.

 * This isn_t good code. The programmer forgot some
 * of the break statements.
import java.util.Scanner;
import java.util.Random;
import static java.lang.System.out;
class BadBreaks {
 public static void main(String args[]) {
  Scanner keyboard = new Scanner(System.in);
  Random myRandom = new Random();
  int randomNumber;
  out.print("Type your question, my child: ");
  randomNumber = myRandom.nextInt(10) + 1;
  switch (randomNumber) {
  case 1:
   out.println("Yes. Isn't it obvious?");
  case 2:
   out.println("No, and don't ask again.");
  case 3:
   out.print("Yessir, yessir!");
   out.println(" Three bags full.");
  case 4:
   out.print("What part of 'no'");
   out.println(" don't you understand?");
  case 5:
   out.println("No chance, Lance.");
  case 6:
   out.println("Sure, whatever.");
  case 7:
   out.print("Yes, but only if");
   out.println(" you're nice to me.");
  case 8:
   out.println("Yes (as if I care).");
  case 9:
   out.print("No, not until");
   out.println(" Cromwell seizes Dover.");
  case 10:
   out.print("No, not until");
   out.println(" Nell squeezes Rover.");
   out.print("You think you have");
   out.print(" problems?");
   out.print(" my random number");
   out.println(" generator is broken!");

In the first run of this code, the randomNumber is 7. The program executes cases 7 through 10, and the default. In the second run, the randomNumber is 3. The program executes cases 3 and 4. Then, because case 4 has a break statement, the program jumps out of the switch and displays Goodbye.


The switch statement is missing some break statements. Even without these break statements, the code compiles with no errors. But when you run the code, you don’t get the results that you want.