Java 17 Recipes
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
How It Works
The switch statement is a control-flow statement that allows you to execute different blocks of code based on the value of a switch expression. It is similar to the if-then- else statement, except that the switch statement can have only a single test expression. The expression type is restricted to one of several different types. When a switch statement executes, it evaluates the expression against constants contained in the switch statement’s case labels. These case labels are branch points in the code. If the value of the expression equals the value of a case label constant, control is transferred to the section of code that corresponds to the matching case label. All code statements from that point on are then executed until either the end of the switch statement or a break statement is reached. The break statement causes the switch statement to terminate, with control being transferred to the statement following the switch statement. Optionally, the switch statement can contain a default label, which provides a branch point for the case when there is no case label constant that equates to the switch expression value. The SwitchTypeChecker isValidSwitchType() method demonstrates the use of a string as the switch test expression. If you closely study the isValidSwitchType() method, you see that it tests whether a Class object represents a type that corresponds to one of the valid switch expression types. The method also demonstrates how case labels can be grouped to implement a logical OR conditional test. If a case label does not have any associated code to execute and no break statement, the flow of execution falls through to the next closest case label containing executable statements, thus allowing common code to be executed if the result of the switch expression matches any one of the grouped case constants. Chapter 7 Data SourCeS anD ColleCtionS 254 The RockPaperScissors class implements a command-line rock-paper-scissors game, playing against the computer. There are two methods in this class that demonstrate the switch statement. The getHand() method shows an enum variable in the switch expression. The playHands() method simply intends to show that although often a variable, the switch expression can be any expression whose result is of one of the allowed switch types. In this case, the expression uses a ternary operator that returns an int value. Download 3.2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling