Java Switch
The switch statement allows a variable to be checked for equality against a list of values that are defined in the code.
Each value is defined as the case, and the variable being switched is checked for each switch case.

Syntax:-
switch(expression) { case constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have N number of case statements */ default : /* Optional */ statement(s); /* If the above case matched or not. Default case always to be executed.*/ }
public class Switch { public static void main(String []args) { int a=0; System.out.println("Print the value of a: "+a); switch(a){ case 0: System.out.println("value is zero"); break; case 1: System.out.println("value is one"); break; case 100: System.out.println("value is hundred"); break; default: System.out.println("value is not 10, 50 or 100"); } } }
Nested Switch Statement:-
Nested Switch Statement is used switch statement inside another switch.
Example:-
public class Nestedswitch { public static void main(String []args) { int a = 1, b = 2; switch(a) { case 1: System.out.println("The value of a in switch: "+ a ); case 2: switch(b) { case 2: System.out.println("The value of b in nested switch:"+ b ); } break; default: System.out.println("value is not 1, 2 "); } } }
Rules in switch statements
- Only one case is selected per execution for the switch statement.
- The value of expression identifies which case is selected.
- The expression must evaluate to byte, short, char, or int primitive data, a String, or a few other types.
- The type of expression and the type of the labels must be agreed.
- Each label shall be an integer literal (as 0, 23, or 'A'), a String literal (like "green"), but not an expression or variable.
- May have any number of statements in one statement List.
- The statement List is usually followed by the break;
- Switch case should have at most one default label.
- If no case label matches the value of the expression, then the default case will be picked, and then statements execute.
Quickly Find What You Are Looking For
Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.