Switch Statement in Java

I hope you have learnt Java if-else statement. In this chapter, we’ll learn the switch statement in java.

Java switch statement can be an extension to the long if-else ladder. It makes your codes more clean and readable. Based on a single expression switch statement can execute multiple blocks of code.

1. Switch Statement in Java:

Syntax:

switch(expression) {
  case value1:
    // code block
    break;
  case value2:
    // code block
    break;
  default:
    // code block
}

Let us understand the syntax:

  • expressions are compared with the values of each case.
  • break and default are optional.
  • when none of the cases is true. default is executed.
  • If the break keyword is not used, then all statements will be executed.
  • We can have any number of case statements.

Example:

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

		int week = 4;
		String weekDay;

		switch (week) {
		case 1:
			weekDay = "Sunday";
			break;
		case 2:
			weekDay = "Monday";
			break;
		case 3:
			weekDay = "Tuesday";
			break;
		case 4:
			weekDay = "Wednesday";
			break;
		case 5:
			weekDay = "Thursday";
			break;
		case 6:
			weekDay = "Friday";
			break;
		case 7:
			weekDay = "Saturday";
			break;
		default:
			weekDay = "Invalid day";
			break;
		}
		System.out.println(weekDay);
	}
}

Output:

Wednesday

Points to Remember:

  • Duplicate case values are not allowed.
  • default statement doesn’t need any break.
  • break keyword is used to terminate the switch statement.
  • Switch Statement will only work with

2. Java Default Keyword:

Java default keyword is used when none of the cases is true. Also, the default statement doesn’t need any break keyword.

int day = 3;
switch (day) {
	case 6:
	 System.out.println("Saturday");
	 break;
	case 7:
	 System.out.println("Sunday");
	 break;
	default:
	 System.out.println("It's not Weekend");
}

3. Java Break Keyword:

If no break keyword is used in the program, the flow of control will drop through all the consequent cases until a break is reached or the closing curly brace ‘}’ is reached.

In Java, switch statement break keyword plays a very major role and it’s recommended to use a break statement because it saves a lot more time because it ignores the rest of the execution in the program.

I hope you’ve understood What is Switch Statement in Java?