Breaks and cases | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Breaks and cases

I guess you might wanna leave it without breaks if more than one case can have the expected effect, you don't want it to stop comparing once one of the cases matches and other cases hasn't been checked yet ? default will be necessary so it doesn't loop endlessly if no break is used?

30th Aug 2017, 7:36 PM
Yuko
Yuko - avatar
2 Answers
+ 2
the switch doesn't cycle at all. if none of the options is matched and there is no default, the execution of the program simply runs through the switch without execution anything. the default stands for "if the variable doesn't match any of the above listed values, do this". You can omitt it if you're 100% sure your variable won't get a value that isn't among the ones listed inside the switch if you don't put a break, you'll get as output anything from the right case to the next break. E.g. int x = 5 switch (x){ case 3: system.out.print(''A''); break; case 5: system.out.print(''B''); case 7: system.out.print(''C''); default: system.out.print(''D''); break; } this outputs BCD
30th Aug 2017, 7:54 PM
Michael Vigato
Michael Vigato - avatar
+ 5
A switch is not a loop, so there won't be an infinite loop (if you didn't put an extra loop around the switch statement). You can definitely use this so called 'fall through'. But if you work on a team, you should add a comment that you want this fall through behaviour. To avoid confusion ;)
30th Aug 2017, 7:53 PM
Tashi N
Tashi N - avatar