Loading

Switch case

  •  A switch is a multiple-choice decision-making statement.
  •  In this statement, there are various types of cases.
  •  If any case matches the input (expression), then that particular case will execute.
  • The break keyword is used to break the statement execution.

Syntax:

switch(expression){    
case A:    
 //code block;    
 break; 
  //optional  
  case B:    
 //code block;    
 break;  
 default:  
    // code block
  }

Example:

package quipohouse;
public class SwitchCase {
	public static void main(String[] args) {
		int day = 3;
		switch (day) {
		case 1:
			System.out.println("Monday");
			break;
		case 2:
			System.out.println("Tuesday");
			break;
		case 3:
			System.out.println("Wednesday");
			break;
		case 4:
			System.out.println("Thursday");
			break;
		case 5:
			System.out.println("Friday");
			break;
		case 6:
			System.out.println("Saturday");
			break;
		case 7:
			System.out.println("Sunday");
			break;
		}
	}
}

Output:

Wednesday

Use of break in switch case :

  •  The break keyword breaks the statement execution.
  • If we do not add the break keyword in the switch case then all onward cases will execute till the break keyword is encountered.

Example-1:

package quipohouse;
public class SwitchCase {
	public static void main(String[] args) {
		int day = 1;
		switch (day) {
		case 1:
			System.out.println("Monday");
		case 2:
			System.out.println("Tuesday");
		case 3:
			System.out.println("Wednesday");
		case 4:
			System.out.println("Thursday");
		case 5:
			System.out.println("Friday");
		case 6:
			System.out.println("Saturday");
		case 7:
			System.out.println("Sunday");
		}
	}
}

Output:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Example-2:

package quipohouse;
public class SwitchCase {
	public static void main(String[] args) {
		int day = 1;
		switch (day) {
		case 1:
			System.out.println("Monday");
		case 2:
			System.out.println("Tuesday");
		case 3:
			System.out.println("Wednesday");
		case 4:
			System.out.println("Thursday");
			break;
		case 5:
			System.out.println("Friday");
		case 6:
			System.out.println("Saturday");
			break;
		case 7:
			System.out.println("Sunday");
		}
	}
}

Output:

Monday
Tuesday
Wednesday
Thursday

Use of default in a switch case statement:

  • If the expression does not match any of the conditions then the default block will execute.

Example:

package quipohouse;
public class SwitchCase {
	public static void main(String[] args) {
		int day =10;
		switch (day) {
		case 1:
			System.out.println("Monday");
			break;
		case 2:
			System.out.println("Tuesday");
			break;
		case 3:
			System.out.println("Wednesday");
			break;
		case 4:
			System.out.println("Thursday");
			break;
		case 5:
			System.out.println("Friday");
			break;
		case 6:
			System.out.println("Saturday");
			break;
		case 7:
			System.out.println("Sunday");
			break;
		default:
			System.out.println("Enter valid input!!");
		}
	}
}

Output:

Enter valid input!!