Java provides a several branch variety statement known as switch. This selection statement checks the significance of an expression against a list of integer or char constants. When a match is found , the statements associated with that constant are executed.
The syntax of the switch statement is as follows : –
case constant1 : statement sequence 1 ;
case constant2 : statement sequence 2 ;
case constant3 : statement sequence 3 ;
default : statement sequence when provided input is not in any of the above cases ;
Use break statement or also you will have a situation called fall through , Its the fall of control to the following case of the matching case.
Here is the proper syntax for the switch statement:
first block to execute
second block to execute
block to execute if n doesn’t match with case 1 and case 2
At the start, the set will have an expression n that needs to be evaluated once. The value of n will then be compared with the value in every case. If it matches with one of the cases, the block of codes under it will be executed. Inserting break; after each condition avoids the code from going over to the next case.