Java Switch Statement Example

I don’t see the switch statement used very much, but it’s on your syllabus so let’s take a look at it:

String grade = input(); // assume that input method exists
String msg;
switch (grade) {
	case "A":
		 msg += "Very ";
	case "B":
		 msg += "Good ";
	case "C": 
		 msg += "Pass";
		 break;
	case "D":
		 msg = "Borderline ";
	case "F":
		 msg = "Fail";
		 break;
	default: 
		 msg = "Invalid Grade";
}
System.out.println(msg);

The outputs are as follows:

grade = “A” -> “Very Good Pass”
grade = “B” -> “Good Pass”
grade = “C” -> “Pass”
grade = “D” -> “Borderline Fail”
grade = “F” -> “Fail”
Anything else -> “Invalid Grade”

Notes:

  • You have to have the break statement otherwise you “fall through” to the next case. It’s normal to have a break statement at the end of every case. The example I’ve provided is contrived to show you the functionality, but in 25 years of programming Java I can’t remember genuinely using a switch statement like this!
  • The default case is executed if none of the other cases are executed.
  • The ability to use a switch statement on String objects was introduced in Java 7.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s