![]() What if we have to execute multiple statements before returning any value from a given case block. In the above example, we are writing only the return value in the case statements. 11 where we are directly assigning the value of the switch statement to the variable result. Let us rewrite the last example, with a switch expression. It is very similar to other normal Java statements. Java 12 introduced the switch expressions which can compute the value for the whole switch statement and assign its value to a variable. ![]() public static Boolean isWeekDay(Day day)Ĭase MON, TUE, WED, THUR, FRI -> result = true ĭefault -> throw new IllegalArgumentException("Invalid day: " + day.name()) We can remove the break statements using the new arrow syntax. In the above example, having the break statements does not look good. As we see that multiple case labels are returning the same value, so we can group the case labels to make the code more readable. The above example works as expected, but we can make it better. Throw new IllegalArgumentException("Invalid day: " + day.name()) Notice how we have created a total of eight case labels that return an appropriate true or false value. For storing all the days in a week, we have created an enum. In this example, we are checking if today is a weekend or weekday, using the switch statement. ![]() We can easily guess that the use of a break statement inside the default label is not necessary because the default label is the last label in the switch statement and the execution of the switch statement will stop after that anyway. If the value of the expression does not match any case label, execution starts at the statement following the optional default label and continues until the end of the switch statement or the break statement is encountered.If the value of the expression matches a case label, the execution starts from the matched case label and executes all statements until the break statement is encountered. Second, the value of expression is matched against the value of each case label.The datatype of the expression value and case labels must be same.First of all, the switch expression is evaluated.Execution FlowĪ switch statement is evaluated as follows: We can achieve similar functionality with a chain of if-else blocks, but the switch statement is more readable and clean. Here labelOne, labelTwo and labelThree are “ compile-time constant expressions” or constants (the value of the labels must be known at compile-time). The expression value must be one of the following 6 types: The general form of a switch statement is – switch (expression) Case Label Values Must be in Range of DataType Better instanceof checking with Switch Statements
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |