Using a string to control a switch statement
Before JDK 7, the switch could only be controlled by integer types such as int or char.
This limited switch usage when action selection was based on the contents of a String.
In these cases, it was common to use an if-else-if ladder.
With JDK 7, it became possible to use String to control switches, making the code more readable and optimized in various situations.
Example:
Output:
Canceling
The switch checks the value of command against the case constants, executing the code corresponding to the first match found.
Using switch with String can improve code readability and is more convenient than a sequence of if/else.
However, using a switch with a String may be less efficient than using a switch with an integer.
It is recommended to use switch with String only when the control data is already in that form, avoiding unnecessary use.
The above is the detailed content of String to control a switch statement. For more information, please follow other related articles on the PHP Chinese website!