Why should I always use break with a switch ?
switch (foo) { case 0: case 1: bar(); break; default: break; } For example, here, both at 0 and at 1, the bar() method is called?
Why should I always use break with a switch ?
switch (foo) { case 0: case 1: bar(); break; default: break; } For example, here, both at 0 and at 1, the bar() method is called?
The switch is made in such a way that when the required element is found, it “fails”. For example, you have a 10-digit switch from 1 to 10. When you transmit 5 for comparison, the switch will be compared in order with 1,2,3,4,5. At this point, the values will coincide further, if no break is indicated, the code will be executed, in the 5,6,7,8,9,10 case. You have no break in the case 0, so your method is executed. add a break and everything will be ok.
Perhaps it will be clearer if we consider the "case x:" as the "entry point", upon entering which you "fall" through a set of commands. The command "break" - "stops" your "fall" (if necessary). Here is a good example.
public class SwitchExample { public static void main(String[] args) { byte x = (byte)(Math.random()*10); //случайный этаж System.out.println("Выпал из окна " + x + " этажа"); x--;//падаем через этажи, расположенные ниже switch (x) { case 9:System.out.println("Пролетаю 9 этаж"); case 8:System.out.println("Пролетаю 8 этаж"); case 7:System.out.println("Пролетаю 7 этаж"); case 6:System.out.println("Пролетаю 6 этаж"); case 5:System.out.println("Пролетаю 5 этаж"); System.out.println("зацепились - ниже не падаем"); break; case 4:System.out.println("Пролетаю 4 этаж"); case 3:System.out.println("Пролетаю 3 этаж"); case 2:System.out.println("Пролетаю 2 этаж"); case 1:System.out.println("Пролетаю 1 этаж"); case 0:System.out.println("На земле"); break;//ниже земли не падаем default:System.out.println("Странно"); } } } Why should I always use break with a switch statement?
Obviously, to tell the compiler where the processing of each case ends.
Source: https://ru.stackoverflow.com/questions/743515/
All Articles