Using a string to control a switch
statementBefore JDK 7, the switch could only be controlled by integer types such as int or char.
This limited the use of switch when the 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:
Exit:
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 switch with String may be less efficient than using integers.
It is recommended to use switch with String only when the control data is already in that form, avoiding unnecessary use.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3