Using the Switch/Case Statement

jeffheaton's picture
Get the entire book!
Java for the Beginning Programmer

You can also use switch/case statements in place of the if/else ladder. Switch/case statements only work with integers, they do not work with strings. So if you want to compare a string, you will have to use an if/else ladder.

A switch/case contains a switch statement with many cases inside of it. Each case specifies what should be done when the case statement's number is passed to the switch statement. Finally a default, at the end, specifies what to do if none of the cases matched.

Listing 5.6 shows the number program, from the last section, rewritten as a switch/case program.

Listing 5.6: Using Switch/Case (NumberCase.java)

import java.io.*;

class NumberCase
{
  public static void main(String args[])
  {
    try
    {
      InputStreamReader inputStreamReader = 
        new InputStreamReader ( System.in );
      BufferedReader in = 
        new BufferedReader ( inputStreamReader );
      System.out.print(
        "Enter a number between 1 and 5? ");
      String num = in.readLine();
      int number = Integer.parseInt(num);

      switch( number )
      {
        case 1:
          System.out.println("You entered One.");
          break;
        case 2:
          System.out.println("You entered Two.");
          break;
        case 3:
          System.out.println("You entered Three.");
          break;
        case 4:
          System.out.println("You entered Four.");
          break;
        case 5:
          System.out.println("You entered Five.");
          break;
        default:
          System.out.println(
    "You did not enter a number between 1 and 5.");
          break;
      }
    }
    catch(NumberFormatException e)
    {
      System.out.println(
        "You must enter a valid number.");
    }
    catch(IOException e)
    {
    }
  }
}

As you can see there is a case for each of the numbers to be compared. At the end there is a default that specifies what to do if none of the cases match.

Very important! Notice how each of the cases ends with a “break” statement? This is required to cause your program to exit the switch block. If you leave out the break, the program will begin executing the next case, and keep on going, until it hits a break.


Copyright 2005 - 2012 by Heaton Research, Inc.. Heaton Research™ and Encog™ are trademarks of Heaton Research. Click here for copyright, license and trademark information.