Switch statement in Java

It is also called as switch case.

Switch case = Switch to a case.

Switch case means switch the control to the specific case or condition.

It can be used instead of a else if ladder in the case if we don't need condition checking one by one like else-if ladder.

It is faster than else-if ladder because the control transfers directly to the case, it does not check condition one by one like else-if ladder.

General Syntax

switch(int or char value) {

case int/char:

//body or statements

break;

case int/char:

//body or statements

break;

default:

//body or statements

break;

}

char, String and int datatypes can be passed as switch parameters.

default keyword is used to specify default case.

break is given after the cases, if not cases below the satisfied case will also gets executed. To stop that we are using break.

Imagine you want to buy a bag in the market. You will not check each store in the market whether bag is available, you will go directly to any bag store. Right ?

How will you solve the above using programming ?

public class SwitchCase {

public static void main(String args[]) {

int wanted=3;

switch(wanted){

case 1:

System.out.print("Restaurant");

break;

case 2:

System.out.print("Dress store");

break;

case 3:

System.out.print("Bag store");

break;

}

}

}

Try In Editor

Output

Bag store