Switch Case Statement
Instead of defining multiple if else block for each condition, we can use switch statement. Based on the choice Switch statement selects specified block of statements to execute.
Syntax:
switch(choice){
case choice1:
//statements
break;
case choice2:
//statements
break;
case choice3:
//statements
break;
default:
//statements: will execute when none of the choice matches
}
Note: You can have any number of cases.
-break and default are optional here
-break and default are optional here
For Example: Simple Calculator using Switch Case
String choice = "multiply";
int a= 4, b= 2;
int res;
switch (choice) {
case "add":
res=a+b;
System.out.println("Addition of a and b: " + res);
break;
case "subtract":
res=a-b;
System.out.println("Subtraction of a and b: " + res);
break;
case "multiply":
res=a*b;
System.out.println("Multiplication of a and b: " + res);
break;
case "divide":
res=a/b;
System.out.println("Division of a and b: " + res);
break;
default:
System.out.println("None of the operation is executed..");
}
int a= 4, b= 2;
int res;
switch (choice) {
case "add":
res=a+b;
System.out.println("Addition of a and b: " + res);
break;
case "subtract":
res=a-b;
System.out.println("Subtraction of a and b: " + res);
break;
case "multiply":
res=a*b;
System.out.println("Multiplication of a and b: " + res);
break;
case "divide":
res=a/b;
System.out.println("Division of a and b: " + res);
break;
default:
System.out.println("None of the operation is executed..");
}
Output: Multiplication of a and b: 8
Continue Learning: break and continue statement
Comments
Post a Comment