0
Uses for switch
I'm learning about how to use switch, but I have doubts about when I need to use it. Please, give me some examples in a real situation where I need to use switch. Another thing, is the switch expression always equality? or can You use greater than, not equal.. etc..? Is the data type of the switch always int?
5 Antworten
+ 31
1. If you have too many conditions to check, using if-else requires writing too long codes. In that case, switch can simplify the whole thing.
Example : Take input of a number (1-12) and output the corresponding month. Take a char input and check whether it's vowel or not. etc.
2. You can check only equality using switch in Java as far as I know.
3. In Java, you can use int, char and String as switch variable.
I'm attaching a sample code here. In this example, a month number (1-12) is input and the number of days in that month should be output. This problem can be solved with very short code if we use switch statement and break properly.
https://code.sololearn.com/cfPuvihedThI/?ref=app
+ 27
Good info @Hadi :)
+ 2
Thanks to Shamima Yasmin.
According to Oracle documents:
A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer
+ 1
Implementing a state machine is good and practical example for usage of switch-case.
+ 1
Thanks :D