Switch


Switch:

It is a multiway branch statement. It provides easy way to divert execution to different parts of our code based on value of an expression. It is often better alternative to large if-else-if chain.

Syntax:

switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
.
case valueN :
// statement sequence
break;
default:
// default statement sequence
}

If a case value matches with the given switch expression then it is executed and
break; statement is used to jump out of the switch block.

Code Example:

Com.knowledge2life class Switch { public static void main(String[] args) { int print = 2; switch (print) { case 1: System.out.println("Knowledge2life 1"); break; case 2: System.out.println("Knowledge2life 2"); break; case 3: System.out.println("Knowledge2life 3"); break; case 4: System.out.println("Knowledge2life 4"); break; } } }

Output:

Knowledge2life 2

Note: Case statements are evaluated and executed in order they are written, starting from the first matched case value. Therefore, if we do not mention break; statement all the subsequent case statements will get executed until the break statement is found. To understand this scenario.
Let's look into following program to understand above point.

Example No.2:

Com.knowledge2life class SwitchCaseExample1 { public static void main(String args[]){ int num=2; switch(num+5) { case 1: System.out.println("Case1: Value is: "+num); case 2: System.out.println("Case2: Value is: "+num); case 3: System.out.println("Case3: Value is: "+num); default: System.out.println("Default: Knowledge2life "); } } }

OUTPUT:

Default: Knowledge2life!