Konstantina Dimtsa

About Konstantina Dimtsa

Konstantina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she is currently pursuing M.Sc studies in Advanced Information Systems at the same department. She is also working as a research associate for NKUA in the field of telecommunications. Her main interests lie in software engineering, web applications, databases and telecommunications.

Java Switch-Case Example

Java provides decision making statements so as to control the flow of your program. These statements are:

  • if...then
  • if...then...else
  • switch..case

In this example, we will show how to use the switch case statement. A switch statement checks if a variable is equal to a list of values. The variable in the switch statement can be a byte, short, int, or char. However, Java 7 supports also switch statements with Strings. We will see such an example in the next sections.

1. Syntax of switch case

The syntax of a switch case statement is the following:

switch (variable) {
  case c1:
        statements // they are executed if variable == c1
        break;
  case c2: 
        statements // they are executed if variable == c2
        break;
  case c3:
  case c4:        
        statements // they are executed if variable ==  any of the above c's
        break;
  . . .
  default:
        statements // they are executed if none of the above case is satisfied
        break;
}
  • switch: the switch keyword is followed by a parenthesized expression, which is tested for equality with the following cases. There is no bound to the number of cases in a switch statement.
  • case: the case keyword is followed by the value to be compared to and a colon. Its value is of the same data type as the variable in the switch. The case which is equal to the value of the expression is executed.
  • default: If no case value matches the switch expression value, execution continues at the default clause. This is the equivalent of the "else" for the switch statement. It is conventionally written after the last case, and typically isn’t followed by break because execution just continues out of the switch. However, it would be better to use a break keyword to default case, too. If no case matched and there is no default clause, execution continues after the end of the switch statement.
  • break: The break statement causes execution to exit the switch statement. If there is no break, execution flows through into the next case, but generally, this way is not preferred.

2. Example of switch case

Let’s see an example of the switch case. Create a java class named SwitchCaseExample.java with the following code:

SwitchCaseExample.java

package com.javacodegeeks.javabasics.switchcase;

public class SwitchCaseExample {
	public static void main(String[] args) {

		grading('A');
		grading('C');
		grading('E');
		grading('G');
	}

	public static void grading(char grade) {

		int success;
		switch (grade) {
		case 'A':
			System.out.println("Excellent grade");
			success = 1;
			break;
		case 'B':
			System.out.println("Very good grade");
			success = 1;
			break;
		case 'C':
			System.out.println("Good grade");
			success = 1;
			break;
		case 'D':
		case 'E':
		case 'F':
			System.out.println("Low grade");
			success = 0;
			break;
		default:
			System.out.println("Invalid grade");
			success = -1;
			break;
		}

		passTheCourse(success);

	}

	public static void passTheCourse(int success) {
		switch (success) {
		case -1:
			System.out.println("No result");
			break;
		case 0:
			System.out.println("Final result: Fail");
			break;
		case 1:
			System.out.println("Final result: Success");
			break;
		default:
			System.out.println("Unknown result");
            break;
		}

	}

}

In the above code we can see two switch case statements, one using char as data type of the expression of the switch keyword and one using int.

  • Output:
Excellent grade
Final result: Success
Good grade
Final result: Success
Low grade
Final result: Fail
Invalid grade
No result

Below is the equivalent of the switch case statement in the method passTheCourse() using if..then..else:

if (success == -1) {
        System.out.println("No result");
} else if (success == 0) {
	System.out.println("Final result: Fail");
} else if (success == 1) {
	System.out.println("Final result: Success");
} else {
	System.out.println("Unknown result");
}

3. Example of switch case using String

As we mentioned in the introduction of this example, Java SE 7 supports String in switch case statements. Let’s see such an example. Create a java class named StringSwitchCase.java with the following code:

StringSwitchCase.java

package com.javacodegeeks.javabasics.switchcase;

public class StringSwitchCase {
	
	public static void main(String args[]) {
		
		visitIsland("Santorini");
		visitIsland("Crete");
		visitIsland("Paros");
		
	}
	
	public static void visitIsland(String island) {
		 switch(island) {
		  case "Corfu":
		       System.out.println("User wants to visit Corfu");
		       break;
		  case "Crete":
		       System.out.println("User wants to visit Crete");
		       break;
		  case "Santorini":
		       System.out.println("User wants to visit Santorini");
		       break;
		  case "Mykonos":
		       System.out.println("User wants to visit Mykonos");
		       break;
		 default:
		       System.out.println("Unknown Island");
               break;
		 }
	}

}

If we run the above code, we will have the following result:

  • Output:
User wants to visit Santorini
User wants to visit Crete
Unknown Island

4. Download the source code

This was a switch case example in Java. You can download the source code from here: SwitchCaseExample.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close