Switch Example Java Program

Definition

A switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via a multiway branch.

Syntax

switch (expression) {
case value_1 :
     statement(s);
     break;
case value_2 :
     statement(s);
     break;
 .
 .
 .
case value_n :
     statement(s);
     break;
default:
     statement(s);
}

Switch Example Program

class SwitchExample{
	public static void main(String[] args){
		int month = 6;
		switch (month){
			case 1:
				System.out.println("Jan");
				break;
			case 2:
				System.out.println("Feb");
				break;
			case 3:
				System.out.println("Mar");
				break;
			case 4:
				System.out.println("Apr");
				break;
			case 5:
				System.out.println("May");
				break;
			case 6:
				System.out.println("Jun");
				break;
			case 7:
				System.out.println("Jul");
				break;
			default:
				System.out.println("Invalid case");
				break;
		}
	}
}

Sample Output

Output is:
Jun