Switch In JAVA With Example – Complete Tutorial

A switch statement is another useful way to control the flow of program which is mostly used in those cases where we need our program to act on a single variable out of several options available. The switch statement first match the case of variable and then act upon the variable if matched.


Table of Contents

Switch Syntax:

switch (variable expression) {
casevalue1:
code_or_statements_to_be_executed_if _variable == value1
break;
casevalue2: 
code_or_statements_to_be_executed_if _variable== value2
break;
case value3:        
code_or_statements_to_be_executed_if _variable_ ==  value3
break;
  . . .
default:
code_or_statements_to_be_executed_if _variable_does_not_match_any_of_the_above_case
break;
}

switch: In the above syntax switch keyword has variable inside parenthesis which is tested for equality with the cases.

case: The case keyword has value of same data type as of switch variable which is tested with the equality of value of switch variable. The case whose value matched is executed.

default: If none of the case value is matched with the value of switch variable then code inside default is executed.

break: The break is used inside each case so as to break out of switch statement.


Switch Example In JAVA:

Lets create a program to choose a day of week in JAVA using switch.


public class SwitchExample {

	public static void main(String[] args) {
		
		int day = 5;

		switch (day){
		case 1:
		System.out.println("It is Monday");
		break;
		case 2:
		System.out.println("It is Tuesday");
		break;
		case 3:
		System.out.println("It is Wednesday");
		break;
		case 4:
		System.out.println("It is Thursday");
		break;
		case 5:
		System.out.println("It is Friday");
		break;
		case 6:
		System.out.println("It is Saturday");
		break;
		case 7:
		System.out.println("It is Sunday");
		break;
		default:
		System.out.println("Entered wrong input");
		break;
		}

	}

}

Output is:

It is Friday