Switch control Statement in Java

Understanding the "Switch" Control Statement in Java

If we can have conditions and based on conditions if we want to control the flow of execution we can use if, if else or if else if. But there is situation where we cannot able to provide the conditions and we want to control the flow of execution. In this scenario we use different control statement that is "switch".

Basic Syntax of the "switch" Statement

The basic syntax of the "if" statement in Java is as follows:


switch (constant/variable/equation) {
case 1: code
break;
case 2: code
break;
case 3: code
break;
.... default: code
break;
}

The case "x" code will be executed after evaluating the constant/variable/equation. Based on the evaluation result of constant/variable/equation the purticular case will be executed. In switch the control will go directly to the specific case and execute the case. But in if else if structure in order to execute a purtcular else if block system has to evaluate all the if and else if conditions which are defined before the else if block which we want to execute. This happens in a sequenctial manner. But in swtich the control will jump to the purticular case directly. None of the cases are not matching if with the evaluated result of constant/variable/equation then default case will be executed. After every block of case a break statement is to be used. If the break statement is not used then irrespective of the evaluation result the subsequent cases also executed which is not desirable as per the requirements. This is called as Fall through

Example Program to demonstrate switch control statement

Program to addition/subtraction/multiplication/division using switch statement


Output 1


Output 2