Java Switch Case Statement With Programming Examples

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 7, 2024

Learn about the Java Switch Statement, Nested Switch, other variations and usage with the help of simple examples:

In this tutorial, we will discuss the Java Switch statement. Here, we will explore each and every concept related to the Switch statement along with the programming examples and their description.

You will be provided enough examples that will let you understand the topic in a better way and will also enable you to create your programs whenever you are required to use the Switch statement.

Some of the frequently-asked questions are included so that you will be aware of the trending questions that are asked related to the Switch statement.

=> Take A Look At The Java Beginners Guide Here.

Java Switch statement (1)

Java Switch Statement

In this tutorial, we will cover the following variations of the Java Switch statement.

  • Switch statement
  • Nested Switch statement (Inner and Outer Switch)

The Switch statement in Java is a branch statement or decision-making statement that provides a way to execute your code on different cases or parts that are based on the value of the expression or condition. More often than that, Java Switch statement provides a better alternative than the various options available with Java if-else statements.

Syntax:

switch (expression){
  case 1:
    //statement of case 1
  break;
  case 2:
    //statement of case 2
  break;
  case 3:
    //statement of case 3
  break;
.
.
.
  case N:
    //statement of case N
  break;
default;
  //default statement
} 

Java Switch statement

Rules For A Switch Statement

Given below are the important rules for a Switch statement.

  • Duplicate cases or case values are not allowed.
  • The value of the Switch case should be of the same data type as the Switch case variable. For E.g. – if ‘x’ is of integer type in a “switch (x)”, then all the Switch cases should be of integer type.
  • The Java break statements can be used (optional) to terminate the sequence of executables inside a case.
  • The default statement is also optional. Usually, it is present at the end of a Switch statement. The default statement gets executed if none of the Switch cases match with the value of the Switch variable.
  • The value of a Switch case must be a constant and not a variable.

Switch Case Using For Loop

Given below is the example program where we have demonstrated how Java Switch statement works or can be used in the programs. First of all, we have initialized the value of ‘i’ inside for loop and specified the condition.

Then, we have implemented the Switch statement with two cases and one default. The default statement will keep on executing until “i<5”. In this case, it will execute 2 times for “i=3” and “i=4”.

public class example {

	public static void main(String[] args) {

		/*
		 * Switch statement starts here. Added three cases and
		 * one default statement. The default statement will 
		 * keep on executing until i&lt;5. In this case, it will 
		 * execute 2 times for i=3 and i=4.
		 */
		
		for(int i=0; i&lt;5; i++) {
			switch(i){
			case 0:
				System.out.println("i value is 0");
				break;
			
			case 1:
				System.out.println("i value is 1");
				break;
			
			case 2:
				System.out.println("i value is 2");
				break;
				
			default:
				System.out.println("i value is greater than 2 and less than 5");
			
			}

		}
	}	
}

Output:

Switch case using for loop - output

The Break Is Optional

In Switch case Java, the break statement is optional. Even if you remove the break, the control of the program will flow to the next case.

Let’s consider the following example.

public class example {

	public static void main(String[] args) {

		/*
		 * Switch statement starts here. Added 10 cases and
		 * one default statement. Execution will flow through 
		 * each of these cases case 0 to case 4 and case 5 to
		 * case 9 until it finds a break statement.
		 */
		
		for(int i=0; i&lt;=10; i++) {
			switch(i){
			case 0:
			case 1:
			case 2:
			case 3:
			case 4:
				System.out.println("i value is less than 5");
				break;
			case 5:
			case 6:
			case 7:
			case 8:
			case 9:
				System.out.println("i value is less than 10");
				break;
				
			default:
				System.out.println("Default statement");
			
			}

		}
	}	
}

Output

The break is optional - output

Nested Switch Statement

This involves the concept of an inner and outer Switch. We can use an inner Switch as a part of the statement of an outer Switch. This type of Switch statement is called the Nested Switch statement or Switch(Inner) inside a Switch(Outer) is known as a Nested Switch.

Syntax:

switch (count){
  case 1:
    switch (target){
    //nested switch statement
      case 0:
       System.out.println(“target is 0”);
       break;

      case 1:
       System.out.println(“target is 1”);
       break;
}
break;

  case 2:
    //…
} 

Finding ‘a’ And ‘b’ Using Nested Switch

In the below example, we have used Scanner class to input ‘a’ and ‘b’ through the console. Then, we have made use of inner and outer Switch to lay down different cases for the value of both ‘a’ and ‘b’.

The control will flow through these inner and outer Switch statements and if the entered value matches, then it will print the value. Otherwise, the default statement will be printed.

import java.util.Scanner;

public class example {

	public static void main(String[] args) {
		
		int a,b;
		System.out.println("Enter a and b");
		Scanner in = new Scanner(System.in);
		a = in.nextInt();
		b = in.nextInt();
		
		
		// Outer Switch starts here
		switch (a) { 

		// If a = 1 
		case 1: 

			// Inner Switch starts here

			switch (b) { 
			
			// for condition b = 1 
			case 1: 
				System.out.println("b is 1"); 
				break;

			// for condition b = 2 
			case 2: 
				System.out.println("b is 2"); 
				break; 

			// for condition b = 3 
			case 3: 
				System.out.println("b is 3"); 
				break; 
			} 
			break; 

		// for condition a = 2 
		case 2: 
			System.out.println("a is 2"); 
			break; 

		// for condition a == 3 
		case 3: 
			System.out.println("a is 3"); 
			break; 

		default: 
			System.out.println("default statement here"); 
			break; 
		} 
		
	} 
}

Output

Finding a and b using nested Switch

Switch Statement Using String

In JDK 7.0 and above, we are allowed to use String objects in the Switch expression or condition.

Given below is the example where we have used Strings in the Switch statement. We can use Strings in a Switch statement just like Integers.

import java.util.Scanner;

public class example {

	public static void main(String[] args) {

		String mobile = "iPhone";
		switch (mobile) {
		case "samsung":
			System.out.println("Buy a Samsung phone");
			break;
			
		case "iPhone":
			System.out.println("Buy an iPhone");
			break;
			
		case "Motorola":
			System.out.println("Buy a Motorola phone");
		
		}

	}
}

Output

Switch Statement using string

Wrapper In A Switch Statement

JDK 7.0 onwards, the Switch statement also works with the Wrapper class. Here, we are going to demonstrate Java Wrapper in a Switch statement.

In the below example, we have used an Integer class that wraps a value of the primitive type int in an object. Using this class, we have initialized a Wrapper variable ‘x’ with the value 3.

Using the Wrapper variable (inside a Switch Statement), we have defined three different cases along with one default case. Whichever case matches with the value of ‘x’, that particular case will be executed.

public class example {
	
	public static void main(String[] args) {
		
		// Initializing a Wrapper variable
		Integer x = 3;

		// Switch statement with Wrapper variable x
		switch (x) {
		case 1:
			System.out.println("Value of x = 1");
			break;
		case 2:
			System.out.println("Value of x = 2");
			break;
		case 3:
			System.out.println("Value of x = 3");
			break;
			
		// Default case statement
		default:
			System.out.println("Value of x is undefined");
		}
	}
}

Output

Wrapper in a Switch statement

Java Enum In A Switch Statement

In JDK 7.0 and above, the Switch statement works well with Java enumeration. In this section, we will demonstrate the Java enum in a switch statement.

Here, we have created an enum called shoes with four constants that are basically shoe brands. Then, we have stored the enumerator in the reference-variable a1.

Using that reference-variable a1, we have initialized a Switch statement with four different cases. Whichever case matches with the reference-variable value, that particular case will get executed.

/*
 * created an enumeration called shoes
 * with four enumerators.
 */
	enum shoes {
		Nike, Adidas, Puma, Reebok;
	}

public class example {
	public static void main(String[] args) {
		/*
		 * stored enumerator in reference variable a1 for constant = Adidas
		 */
		shoes a1 = shoes.Adidas;

		/*
		 * Started Switch Statement and if the element matches with a1 then it
		 * will print the statement specified in the case
		 */
		
		switch (a1) {
		// does not match
		case Nike:
			System.out.println("Nike - Just do it");

			break;
		// matches
		case Adidas:
			System.out.println("Adidas - Impossible is nothing");
			break;
		// does not match
		case Puma:
			System.out.println("Puma - Forever Faster");
			break;
		// does not match
		case Reebok:
			System.out.println("Reebok - I Am What I Am");
			break;
		}
	}
}

Output

Java enum in a switch statement

Frequently Asked Questions

Q #1) What is a Java Switch statement?

Answer: The Switch statement in Java is a branch statement or decision-making statement (just like the Java if-else statement) that provides a way to execute the code on different cases. These cases are based on some expression or condition.

Mostly, the Java Switch statement has proven to be a better alternative for decision-making than the Java if-else statement.

Q #2) How do you write a Switch statement in Java?

Answer: Given below is a sample program where we have used the Switch statement. Here, we have taken an integer called brand with the value 4 and then used this integer in a Switch statement for different cases.

The brand’s integer value matches the case and then the statement of that particular case will be printed.

import java.util.Scanner;

public class example {

	public static void main(String[] args) {
		
		int brand = 4;
		String name;
		
		// Switch statement starts here
		
		switch(brand){
		case 1: 
			name = "Nike";
			break;
		
		case 2:
			name = "Dolce &amp; Gabbana";
			break;
			
		case 3:
			name = "Prada";
			break;
			
		case 4:
			name = "Louis Vuitton";
			break;
			
		default:
			name = "Invalid name";
			break;
		
		}
		
		System.out.println("The brand name is: " + name);
		
	} 
}

Output

Switch Statement in Java

Q #3) Give a Switch Statement example.

Answer: There are plenty of examples of a Switch statement in this tutorial. We have given all the possible examples, be it Switch with Integer or Switch with String.

You can refer to the examples given at the beginning of this tutorial so that you will be aware of the basics of a Switch statement and how it is used with the loops. (Refer to the “Switch case using for loop” section)

Q #4) Do you need a default case in a switch statement?

Answer: No, it is not mandatory to use the default case whenever dealing with the Switch statement.

For instance, if you see the below example where we have not used a default case. Even though we do not use the default case, the program will execute perfectly as long as it finds the matching case.

import java.util.Scanner;

public class example {

	public static void main(String[] args) {

		String author = "Saket";
		switch (author) {
		case "John":
			System.out.println("John is the author");
			break;
			
		case "Michael":
			System.out.println("Michael is the author");
			break;
			
		case "Rebecca":
			System.out.println("Rebecca is the author");
			break;
			
		case "Saket":
			System.out.println("Saket is the author");
			break;
			
		case "Steve":
			System.out.println("Steve is the author");
			break;
				
		}

	}
}

Output

Switch Statement - example

Conclusion

In this tutorial, we have discussed the Java Switch statement along with the syntax, description, and flowchart. One other variation which is the Nested Switch statement is also discussed in detail with the proper examples including the concept of inner and outer Switch.

Further reading =>> MySQL CASE Statement with examples

Some frequently asked questions are also provided here so that you will be able to know the trending questions related to the Java Switch statement. These decision making statements will be helpful when you want to segregate the code based on some condition or expression and want to check multiple cases.

=> Check ALL Java Tutorials Here.

Was this helpful?

Thanks for your feedback!

Leave a Comment