Previous lesson Back to the front Next lesson

Baby You Can Turn Me On


Hi! This lesson is on something called a switch statement. You use it when you have a lot of choices (like a menu) and you want to do something different for each one. Although there are other ways to do this, they are less efficient (make your program slower) and make it easier to make mistakes.

So let's use the menu as an example. Suppose we are writing part of a program which allows us to see people's details (name, age, etc.).


class Hello {
	public static void main(String[] args) {
		System.out.println("Please select an option (1-3):");
		System.out.println("1  Print name");
		System.out.println("2  Print age");
		System.out.println("3  Exit");
	}
}

So now we have a simple menu printed out. The next part of the program just reads a value as an int from the keyboard. Don't worry about how it works. The only thing you need to know is that the value will be stored in the variable choice. Don't forget the import at the top (this will be explained in another lesson).


import java.io.*;

class Hello {
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

		System.out.println("Please select an option (1-3):");
		System.out.println("1  Print name");
		System.out.println("2  Print age");
		System.out.println("3  Exit");

		int choice = Integer.parseInt(in.readLine());
	}
}

I'll write this program without using the switch statement at all to start with.


import java.io.*;

class Hello {
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

		System.out.println("Please select an option (1-3):");
		System.out.println("1  Print name");
		System.out.println("2  Print age");
		System.out.println("3  Exit");

		int choice = Integer.parseInt(in.readLine());

		if (choice == 1) {
			System.out.println("Ben Golding");
		} else if (choice == 2) {
			System.out.println("20 years");
		} else if (choice == 3) {

		} else {
			System.out.println("Invalid choice " + choice);
		}
	}
}

Right, that's enough of that - let's try it out:

[nurmes]btg: javac Hello.java
[nurmes]btg: java Hello
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
1
Ben Golding
[nurmes]btg: java Hello
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
2
20 years
[nurmes]btg: java Hello
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
3
[nurmes]btg: java Hello
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
7
Invalid choice 7
[nurmes]btg: 

You will have to keep running the program again and again, as it exits whichever option you choose.

Now we're going to add a while loop (remember those?) to keep the program running until we choose option 3. Notice the break statement (I've highlighted it in blue) when we choose the exit option. Go back and check the loops lesson if you don't remember how break works.


import java.io.*;

class Hello {
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

		while (true) {
			System.out.println("Please select an option (1-3):");
			System.out.println("1  Print name");
			System.out.println("2  Print age");
			System.out.println("3  Exit");

			int choice = Integer.parseInt(in.readLine());

			if (choice == 1) {
				System.out.println("Ben Golding");
			} else if (choice == 2) {
				System.out.println("20 years");
			} else if (choice == 3) {
				break;
			} else {
				System.out.println("Invalid choice " + choice);
			}

			System.out.println("-----------------");
		}
	}
}

You should indent all the code that was there before. Try it out, and try entering various values (not just 1, 2 and 3) until you're clear on how the program works.

[nurmes]btg: javac Hello.java
[nurmes]btg: java Hello
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
1
Ben Golding
-----------------
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
2
20 years
-----------------
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
7
Invalid choice 7
-----------------
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
3
[nurmes]btg:

I've also added a line to print out a separator (a line of dashes) each time we go around the loop again. Notice it isn't printed after we choose option 3 because of where the break statement is.

Right, now we're going to try to rewrite this exact same program without using if or else. To do that, we need to switch.


import java.io.*;

class Hello {
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

		while (true) {
			System.out.println("Please select an option (1-3):");
			System.out.println("1  Print name");
			System.out.println("2  Print age");
			System.out.println("3  Exit");

			int choice = Integer.parseInt(in.readLine());

			switch (choice) {

			}

			System.out.println("-----------------");
		}
	}
}

Don't try to compile it yet! I've thrown away all the iffy stuff, but we need to explain about switch a bit before we have a complete program.

So then - the first thing we have with a switch statement is a block like that one above. In the round brackets we put an expression which gives us an integer (byte, short, int or long). Usually this is just the name of a variable, like in our example. We are also allowed to use chars, because they are really just the same as shorts (16 bit whole numbers).


import java.io.*;

class Hello {
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

		while (true) {
			System.out.println("Please select an option (1-3):");
			System.out.println("1  Print name");
			System.out.println("2  Print age");
			System.out.println("3  Exit");

			int choice = Integer.parseInt(in.readLine());

			switch (choice) {
			case 1:
				System.out.println("Ben Golding");
			case 2:
				System.out.println("20 years");
			}

			System.out.println("-----------------");
		}
	}
}

Now it's partly finished. I expect you can guess how this works. We look at the value of choice and jump to the piece of code under the appropriate case. Before we add any more to this, let's try it out.

[nurmes]btg: javac Hello.java
[nurmes]btg: java Hello
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
1
Ben Golding
20 years
-----------------
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
2
20 years
-----------------
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
1
Ben Golding
20 years
...

When you get bored of doing that, hold down the Ctrl key and press C to kill the program (we haven't done exit yet). It looks like there's a problem, doesn't it? The problem is that the switch jumps to the appropriate case and then continues on to the end of the switch's block. So when choice is 1, it continues on to the code under case 2 too.

The way to avoid this is to write break, which causes the program to jump to the end of the switch. Although it is optional, in most cases we write break just before the next case.


import java.io.*;

class Hello {
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

		while (true) {
			System.out.println("Please select an option (1-3):");
			System.out.println("1  Print name");
			System.out.println("2  Print age");
			System.out.println("3  Exit");

			int choice = Integer.parseInt(in.readLine());

			switch (choice) {
			case 1:
				System.out.println("Ben Golding");
				break;
			case 2:
				System.out.println("20 years");
				break;
			}

			System.out.println("-----------------");
		}
	}
}

The second break doesn't actually make any difference, because it is at the very end of the block belonging to the switch statement. I put it there just to be safe.

Now it should work:

[nurmes]btg: javac Hello.java
[nurmes]btg: java Hello
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
1
Ben Golding
-----------------
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
2
20 years
-----------------
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
1
Ben Golding
...

Unfortunately now we have a problem with making the program exit, because we used break for that before. In this case we can use return instead, which finishes the main method.

If we have a while inside a while, or a switch inside a while for example, the break only applies to the inner one. We can get around this problem by saying where to break to, as I will show you later in this lesson.

Anyway, let's fix the exit option.


import java.io.*;

class Hello {
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

		while (true) {
			System.out.println("Please select an option (1-3):");
			System.out.println("1  Print name");
			System.out.println("2  Print age");
			System.out.println("3  Exit");

			int choice = Integer.parseInt(in.readLine());

			switch (choice) {
			case 1:
				System.out.println("Ben Golding");
				break;
			case 2:
				System.out.println("20 years");
				break;
			case 3:
				return;
			}

			System.out.println("-----------------");
		}
	}
}

So let's assume that works (you can try it in a minute). What about if we enter an invalid value like 7? Previously we used the last else to deal with it. In switch we write default (instead of another case). If none of the cases match the value, we go to the default. It's very easy so I'll just show you:


import java.io.*;

class Hello {
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

		while (true) {
			System.out.println("Please select an option (1-3):");
			System.out.println("1  Print name");
			System.out.println("2  Print age");
			System.out.println("3  Exit");

			int choice = Integer.parseInt(in.readLine());

			switch (choice) {
			case 1:
				System.out.println("Ben Golding");
				break;
			case 2:
				System.out.println("20 years");
				break;
			case 3:
				return;
			default:
				System.out.println("Invalid choice " + choice);
				break;
			}

			System.out.println("-----------------");
		}
	}
}

Again, I've put the last break in when it's not necessary. But see that the break after case 2 is needed now. We could easily have forgotten to add it, if we hadn't earlier.

Now we think everything works, we'd better try it:

[nurmes]btg: javac Hello.java
[nurmes]btg: java Hello
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
1
Ben Golding
-----------------
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
2
20 years
-----------------
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
7
Invalid choice 7
-----------------
Please select an option (1-3):
1  Print name
2  Print age
3  Exit
3
[nurmes]btg:

Fantastic! Now remember earlier in this lesson I said that we can switch on any type of integer (byte, int etc) or a char. Let's use A, B ,C instead of 1, 2, 3 for our menu. This means changing lots of things, including changing the case statements to have characters (between single quotes).


import java.io.*;

class Hello {
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

		while (true) {
			System.out.println("Please select an option (A-C):");
			System.out.println("A  Print name");
			System.out.println("B  Print age");
			System.out.println("C  Exit");

			char choice = in.readLine().charAt(0);

			switch (choice) {
			case 'A':
				System.out.println("Ben Golding");
				break;
			case 'B':
				System.out.println("20 years");
				break;
			case 'C':
				return;
			default:
				System.out.println("Invalid choice " + choice);
				break;
			}

			System.out.println("-----------------");
		}
	}
}

Make sure you use single and not double quotes for the characters. Notice that although a lot of the details have changed, the basic structure of the switch is the same. Let's try the program out again.

[nurmes]btg: javac Hello.java
[nurmes]btg: java Hello
Please select an option (A-C):
A  Print name
B  Print age
C  Exit
A
Ben Golding
-----------------
Please select an option (A-C):
A  Print name
B  Print age
C  Exit
B
20 years
-----------------
Please select an option (A-C):
A  Print name
B  Print age
C  Exit
a
Invalid choice a
-----------------
Please select an option (A-C):
A  Print name
B  Print age
C  Exit
C
[nurmes]btg: 

Good, so it does what we expected. But see when I try a small letter like a, it doesn't work. Let's add a feature so that small letters are allowed too.


import java.io.*;

class Hello {
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

		while (true) {
			System.out.println("Please select an option (A-C):");
			System.out.println("A  Print name");
			System.out.println("B  Print age");
			System.out.println("C  Exit");

			char choice = in.readLine().charAt(0);

			switch (choice) {
			case 'A':
			case 'a':
				System.out.println("Ben Golding");
				break;
			case 'B':
			case 'b':
				System.out.println("20 years");
				break;
			case 'C':
			case 'c':
				return;
			default:
				System.out.println("Invalid choice " + choice);
				break;
			}

			System.out.println("-----------------");
		}
	}
}

Now we can use upper or lower case letters with exactly the same effect.

[nurmes]btg: javac Hello.java
[nurmes]btg: java Hello
Please select an option (A-C):
A  Print name
B  Print age
C  Exit
A
Ben Golding
-----------------
Please select an option (A-C):
A  Print name
B  Print age
C  Exit
b
20 years
-----------------
Please select an option (A-C):
A  Print name
B  Print age
C  Exit
c
[nurmes]btg: 

Now I want to show you one more trick - you won't have to use this very often, but when you do, it's really handy. Remember that I talked about using break to exit from the program? If we just write break, the compiler thinks that we just want to leave the switch statement, so the program doesn't exit (try it). We have to say that we also want to break out of the while loop. The way to do this is to label the while loop, and then give the name of the label when we break.


import java.io.*;

class Hello {
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

		mainLoop:
		while (true) {
			System.out.println("Please select an option (A-C):");
			System.out.println("A  Print name");
			System.out.println("B  Print age");
			System.out.println("C  Exit");

			char choice = in.readLine().charAt(0);

			switch (choice) {
			case 'A':
			case 'a':
				System.out.println("Ben Golding");
				break;
			case 'B':
			case 'b':
				System.out.println("20 years");
				break;
			case 'C':
			case 'c':
				break mainLoop;
			default:
				System.out.println("Invalid choice " + choice);
				break;
			}

			System.out.println("-----------------");
		}
	}
}

The label is the line just before the while. It can be called whatever you like (using the same rules as names of variables), so long as the break uses the same name. Now try the program and you will find that it exits correctly.

Play about with this as much as you like - try adding your own options to the menu and testing them. I'm finished with you for now, so please fill out the questionnaire before you go.

But
what
do
you
think?
This lesson was...
What don't you understand? Other comments?
Excellent
OK
Poor
Your email (optional)
This is the End

Too patronising? Too complex? Typing error? Offended by traffic cones? Got a question or something I should add? Send an email to ben_golding@yahoo.co.uk !

visits to this site

The contents of this site are copyright of Ben Golding