Switch Code Segments


Introduction.  We have one last major decision related control structure to examine.  Think of situations where you have many different options such as a fairly large variety of command buttons on a form.  Many situations don't require developing a mathematical expression for each possibility as we saw with the If (expression)  Else If (expression).  These sorts of situations where there are a fairly large variety of readily identifiable conditions for altering program flow can often best be implemented using switch code segments.

The basic syntax for the switch control structure follows.

Switch (discreteVariable)

case value1:

program statements that are executed if
the discreteVariable takes on value1;


case value2:

program statements that are executed if
the discreteVariable takes on value2;


. . .


these program statements are executed by default;



Some Verbal Examples.  We will start with some relatively common language examples and then progress to computer code.

get which year in college for input

switch (classRank)

case 1:

you are a freshman;


case 2:

you are a sophomore;


case 3:

you are a junior;


case 4:

you are a senior;



While there is some obvious imprecision in our approach to determining whether someone is a freshman, sophomore, junior or senior you should get the idea.

The switch variable must be either a byte, short, int or char.  Notice the first three are numbers with no decimal places.

We will present two examples, one that is based on an integer input, the other is based on character input.

A Switch Based on a Number.  In order to do something really scientific we are going to tell you everything you need to know about yourself based on your age.  Unfortunately, this will probably be higher quality science than far too many things that try to masquerade under this impressive and overused term.  You should call the applet AgePredictions.java.


import javax.swing.JOptionPane;
import javax.swing.JApplet;

public class AgePredictions extends JApplet

public void init()

String userEntry;
int intUserEntry = 0;
boolean acceptableInput = true;

// Prompt user for input
userEntry = JOptionPane.showInputDialog("Please enter your age as an integer:");

// convert this string value to an integer

intUserEntry = Integer.parseInt(userEntry);


catch (NumberFormatException nfeInteger)

JOptionPane.showMessageDialog( null, "The entry needs to be an integer",
"Not a Number", JOptionPane.INFORMATION_MESSAGE);
acceptableInput = false;


// the basis of a switch must be discrete
if (acceptableInput)

switch (intUserEntry)

case 1: case 2: case 3: case 4: case 5:
case 6: case 7: case 8: case 9: case 10: case 11:
JOptionPane.showMessageDialog( null, "UGH! You're too smart to be in this class",
"Age Predictions", JOptionPane.INFORMATION_MESSAGE);

case 12: case 13: case 14: case 15: case 16: case 17:
JOptionPane.showMessageDialog( null, "Well I'm not sure what you're doing in this class.\nJust don't spew any bodily fluids on this computer!" ,
"Age Predictions", JOptionPane.INFORMATION_MESSAGE);

case 18: case 19: case 20: case 21: case 22:
JOptionPane.showMessageDialog( null, "Ya, right! You think you're smart because you're in college.\nBut we all know you probably had sex with\nan artificial lifeform within the last 24 hours!" , "Age Predictions", JOptionPane.INFORMATION_MESSAGE);

case 23: case 24: case 25: case 26: case 27: case 28:
JOptionPane.showMessageDialog( null, "Do I feel sorry for you,\ntrapped between a bunch of hyperactive classmates\nand a hyperactive prof!" ,
"Age Predictions", JOptionPane.INFORMATION_MESSAGE);

JOptionPane.showMessageDialog( null, "You are unclassifiable!\nThis is probably a compliment" , "Age Predictions", JOptionPane.INFORMATION_MESSAGE);

} // end switch

} // end if statement based on acceptableInput

} // end method init

} // end class AgePredictions


You should be able to create your own AgePredictions.html without my help.

The code can be seen as having three major sections

  • The first section
    • imports the necessary classes fro the appropriate packages
      • JOptionPane from swing
      • JApplet from swing
    • extends JApplet into the overall inclusive AgePredictions class
    • initializes some variables
      • notice we have our first boolean variable that is true or false
  • The second section
    • gets the user's age through the showInputDialog( ) method in the JOptionPane class
    • tries to parse it into an integer
    • catches non-parseable inputs
      • sets the boolean variable associated with appropriate inputs to false
  • The third section
    • is encompassed by an if (expression) statement so that it will execute only if the boolean acceptableInput is true
    • contains the switch statement based on the input
    • contains cases composed of multiple values
      • uses the showMessageDialog( ) method of JOptionPane to display an appropriately insightful message
      • uses the break statement to make certain none of the other cases, particularly the default, is executed after it
      • executes the default case if none of the other cases is satisfied

Notice how the indentation gets pretty deep.  But this can be important when debugging.

A Switch Based on a Character.  Now for something completely different, we will work with an applet that draws something in the applet window.  The user's inputs are used to determine whether a line, rectangle or oval should appear.  You should call the applet SwitchTest.java.


import javax.swing.*;
import java.awt.Graphics;

public class SwitchTest extends JApplet


int i;
char choice[];

public void init( )

String strChoice;

strChoice = JOptionPane.showInputDialog(
"Enter a to draw a line\n" +
"Enter b to draw a rectangle\n" +
"Enter c to draw an oval\n");

choice = strChoice.toCharArray();

} // end init( )

public void paint ( Graphics g )

switch( choice[0] )

case 'a':
g.drawLine(10, 10, 250, 30);
case 'b':
g.drawRect( 20, 50, 70, 100 );
case 'c':
g.drawOval( 40, 60, 80, 120 );
JOptionPane.showMessageDialog(null, "Invalid value was entered");

} // end switch

} // end paint( )

} // end SwitchTest


Since the size of the applet window is important here is the SwitchTest.html.


<applet code="SwitchTest.class" width=300 height=250>


Make sure you try entering a number of different values by using the restart option in the drop down box on the applet window.

This code can be viewed as having three major sections.  We don't have the usual error trapping since we have the default in the switch statement and everything can be brought in as a string.

  • Imports, declarations and initialization
    • imports
      • this time we import everything in swing
      • the Graphics classes are imported from the awt - abstract windowing toolkit package
    • we declare SwitchTest to extend JApplet
    • we declare an integer
    • we declare an array of char to be used for the user's inputs
      • we will not formally study arrays for some time but I need an array of char in order to cast the string input from the showInputDialog( ) method in the JOptionPane class
    • we declare the init( ) method
  • Obtaining inputs and casting them into the appropriate form
    • we obtain the inputs in the usual way with the showInputDialog( ) method in the JOptionPane class
    • there isn't a cast method to convert frm a string to a character so I needed to use the toCharArray( ) method in the String class in order to convert the inputs
      • there may be a better way but I couldn't find it
      • then we base the switch on the very first entry in this array
  • The Paint( ) method containing the switch code segment
    • the Paint( ) method is declared
    • the switch is based on choice[0], the first element in the array of characters that was obtained from the user's inputs
    • each case is based on a letter input
      • the letters are enclosed in single quotation marks
      • each case calls a different method in the Graphics class
        • don't worry about the details of this draw methods unless you have some interest in them

The following image represents a user having selected c for the oval.