Switch Case in Java

Java Switch Statement

switch case in Java is used to execute only one block at a time out of many depending on the value of expression in the switch statement.

Switch Case Syntax

switch(expression) {
  case a:
    // block of code statements
    break;
  case b:
    // block of code statements
  case c:
    // block of code statements
    break;
  default:
    // block of code statements
}

Working of Switch Case

  • The expression in the switch statement is evaluated to a value only once.
  • The values in the case statement (a, b, c) are compared with the value of expression and corresponding block of code is executed.
  • If no value matches with expression value then the default block of code is executed.

Switch Case Example Program in Java

import java.io.*;

public class SwitchCaseExample {

    public static void main(String[] args) {

	String lang = "Java";

	switch(lang)
	{
	case "Python":
		System.out.println("I am learning Python.");
		break;
	case "Java":
		System.out.println("I am learning Java.");
	case "Rust":
		System.out.println("I am learning Rust.");
		break;
	}
    }
}

/* Output of above code:

I am learning Java.

*/
So now you know the use of switch case.

default Statement

Now let's talk about the default and break statements.

The default code block gets executed when no value in case statements matches the value of expression in switch statement.

Modify the above code by replacing switch case with the one given below.
// Also change the value of lang variable to PHP
	String lang = "PHP";

	switch(lang)
	{
	case "Python":
		System.out.println("I am learning Python.");
		break;
	case "Java":
		System.out.println("I am learning Java.");
	case "Rust":
		System.out.println("I am learning Rust.");
		break;
	default:
		System.out.println("'" + lang + "'" + "does not match any value.");
	}
    }
}
Here the default code block will be executed and you will output 'PHP' does not match any value.

The default statement can appear anywhere in the switch case block.

break Statement

break statement is used to separate different cases in the switch.

Now change value of Lang variable to Java again and remove the code>break statement after case Java and observe the change in the output.
// Don't forget to change lang = "Java"

/* Output:-

I am learning Java.
I am learning Rust.

*/
You see that if we don't use break statement consecutive case blocks are executed. To prevent this break is used.