0 0
WP Ad Inserter plugin
Read Time:7 Minute, 9 Second

Table of Contents

With the help of examples, you will learn how to utilize the switch statement in Java to regulate the flow of your program’s execution. The switch statement lets us choose several different ways to run a code block. The switch statement in Java has the following syntax:

Switch statement in Java

switch (expression) { case one: // code break; case two: // code break; ... ... default: // run default statements here }

What is the purpose of the switch-case statement?

The expression is evaluated once, and the values of each case are compared. If the expression matches one, the case one code is triggered. Similarly, if the expression matches two, case two’s code is initiated. If no match is found, the default case’s code is run.

The switch-case statement works similarly to the Java if…else…if. The syntax of the switch statement, on the other hand, is significantly cleaner and easier to read and write.

Example: Java’s switch Statement

// Program for checking the length using the switch...case statement class CodeMain { public static void main(String[] args) { int numVar = 50; String scoreVar; // switch statement for checking the size switch (numVar) { case 80: scoreVar = "Excellent"; break; case 70: scoreVar = "Good"; break; // match the value of week case 60: scoreVar = "Above Average"; break; case 50: scoreVar = "Average"; break; default: scoreVar = "Indefinite"; break; } System.out.println("Your score is: " + scoreVar); }

To find the scoreVar, we utilized the switch statement in the previous example. We have a variable number here. Each case statement’s value is compared to the variable. The code for case 50 is run since the value matches 50.

Break statement in Java’s switch…case

You’ll notice that we’ve used a break in each case block. For instance,


case 50: scoreVar = "Average"; break;

The switch-case statement is terminated with the break statement. If no break is given, all cases after the matching case are also executed. As an example,

class CodeMain { public static void main(String[] args) { int expValue = 3; // switch statement for checking the weight switch (expValue) { case 1: System.out.println("1st Case "); // matching case case 2: System.out.println("2nd Case "); case 3: System.out.println("3rd Case"); case 4: System.out.println("4th Case"); default: System.out.println("Default case"); } }

In the preceding example, expValue corresponds to situation 3. Further, after each instance, we haven’t utilized the break statement. As a result, all cases after case 3 are also run. It is why, following the matching case, the switch-case statement must be terminated with a break statement.

Java switch-case default case

A default case is also included in the switch statement as an option. It is executed when the expression does not fit any of the cases. As an example,

class CodeMain { public static void main(String[] args) { int expVal = 10; switch(expVal) { case 1: System.out.println("Excellent"); break; case 2: System.out.println("Good"); break; case 3: System.out.println("Average"); break; // default case default: System.out.println("out of scope"); } }

A switch-case statement is produced in the preceding example. The value of the expression, in this case, does not match any of the cases. As a result, the default case’s code is executed.

default: System.out.println("out of scope");

Example: A Simple Switch Case

public class CodeSwitchCase{ public static void main(String args[]){ int numVar=10; switch(numVar+5) { case 1: System.out.println("1st Case: Value is: "+numVar); case 2: System.out.println("2nd Case: Value is: "+numVar); case 3: System.out.println("3rd Case: Value is: "+numVar); default: System.out.println("The Default: Value is: "+numVar); } }

We used an expression in the switch, but you can also use a variable. In addition, we gave the equation numVar+5, where numVar is 10, and the result after addition is 15. Because no case with the value 15 was defined, the default case is used. That is why, in the switch scenario, we should use the default so that if no catch meets the condition, the default block is run.


Example: Switch-Case without a break

public class CodeSwitchCase { public static void main(String args[]){ int numVar=5; switch(numVar) { case 1: System.out.println("1st Case "); case 2: System.out.println("2nd Case "); case 3: System.out.println("3rd Case "); case 4: System.out.println("4th Case "); case 5: System.out.println("5th Case "); case 6: System.out.println("6th Case "); case 7: System.out.println("7th Case "); default: System.out.println("No such definition in our cases "); } }

Although the break statement is not required in switch cases, you will always use it. The example above is a scenario where we’re not utilizing the break statement.

We gave integer value 5 to the switch in the above program, which caused the control to switch to case 5, but we didn’t have a break statement after case 5, which caused the flow to transfer to the succeeding cases till the end. The break statement is the solution to this situation.

You use break statements when you wish your program flow to exit the switch body. The execution flow is bypassed when a break statement is discovered in the switch body. Subsequently, the rest of the instances are ignored.

Example: Switch-Case with Break

Let’s use the same example but with a break statement this time.

public class CodeSwitchCaseWithBreak { public static void main(String args[]){ int numVar=5; switch(i) { case 1: System.out.println("1st Case "); break; case 2: System.out.println("2nd Case "); break; case 3: System.out.println("3rd Case "); break; case 4: System.out.println("4th Case "); break; case 5: System.out.println("5th Case "); break; case 6: System.out.println("6th Case "); break; case 7: System.out.println("7th Case "); break; default: System.out.println("No such definition in our cases "); } }

As you can see, only Case 5 was run, while the rest of the cases were ignored. After default, why didn’t we use the break statement? After default, the control would come out of the switch, so we didn’t use it; however, if you still want to utilize the break after default, go ahead; there’s no damage.


Example: Using characters in switch case

public class CodeSwitchCase { public static void main(String args[]){ char charVar='z'; switch(charVar) { case 'a': System.out.println("1st Case "); break; case 'b': System.out.println("2nd Case "); break; case 'c': System.out.println("3rd Case "); break; case 'd': System.out.println("4th Case "); break; default: System.out.println("Default "); } }

Example: Switch Case on Month Variables

//Program for demonstrating the Switch statement by printing the month's name for the given number public class CodeSwitchMonth { public static void main(String[] args) { //indicate the current month's number int monthVar=5; String resultVar=""; //Switch statement switch(monthVar){ //case statements within the switch block case 1: resultVar="1 - January"; break; case 2: resultVar="2 - February"; break; case 3: resultVar="3 - March"; break; case 4: resultVar="4 - April"; break; case 5: resultVar="5 - May"; break; case 6: resultVar="6 - June"; break; case 7: resultVar="7 - July"; break; case 8: resultVar="8 - August"; break; case 9: resultVar="9 - September"; break; case 10: resultVar="10 - October"; break; case 11: resultVar="11 - November"; break; case 12: resultVar="12 - December"; break; default:System.out.println("This is not a valid Month!"); } //Printing the given numbers' month System.out.println(resultVar); } } 


We utilize the switch case statement when we have several possibilities (or choices), and we may need to conduct a different action for each choice. Also, even though it is optional, the Switch Case statement is frequently used with the break statement. So, overall, it is possible to have a switch case without a break statement and a switch case with a break, as we have seen in the examples.

Order 1, 2, 3, and so on are not necessarily required in a case. After the case keyword, it can have any integer value. Furthermore, the case does not always have to be specified in ascending order, depending on the requirement, and you can provide them in any order. Additionally, if the expression given inside the switch does not result in a constant value, it is not valid. Switch statements can be nested, which means you can put one switch statement inside another. On the other hand, nested switch statements are avoided because they make the program more complex and challenging to read.

Source: https://www.codeunderscored.com/switch-statement-in-java-explained-with-examples/

How to use Math.random() method in Java Previous post How to use Math.random() method in Java
Factorial in Python NumPy explained with examples Next post Factorial in Python NumPy explained with examples

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.