1

Hi just learning java lately as a beginner and this fall through thing kinda confused me.

So people say that if you don't add a "break" statement in switch, it will automatically flow through all cases.

case 2:
// Do Something A
case 3:
// Do Something B
break;

However, shouldn't case mean something like "if found the target, then do?". In that case, even if i don't put a break after case 2, that integer 2 still doesn't meet condition case 3 right? So why would it automatically flow through to do something B too even though it doesn't meet the condition "case 3"?

Thanks for helping a newbie out!!

whales
  • 787
  • 1
  • 12
  • 24

3 Answers3

3

You can think of the case as the point you enter the switch and the break where you leave it. It can be useful in a number of situations to have the fall through, say for example you had a number of rewards for a certain level of points, i.e 3 points wins a cat and 4 wins a cat and a dog and 5 wins a cat a dog and a monkey you could write:

switch(points){
   case 5:
       win(monkey);
   case 4:
       win(dog);
   case 3:
       win(cat);
}
Egg Vans
  • 944
  • 10
  • 21
2

It's Java's heritage from the C++ language, which in turn inherited it from the C language.

Nowadays, practical usages of breakthrough are rare, and some editors even add warnings on missing break statements (except for empty cases, e.g. case 1: case 2 : ...).

See also: https://softwareengineering.stackexchange.com/questions/162574/why-do-we-have-to-use-break-in-switch

Community
  • 1
  • 1
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
1

Think in the sense that the code is smart enough to get to where it needs to be, but not smart enough to get back out. Once it is in and has finished its job, the execution thread needs to be told to get back out or it will just keep executing whatever code it is next to.

Therefore, always use a break statement.

case 2: // execute whatever is here..
   break; // now get out
case 3: // so that this doesn't get executed
   break;
Clint
  • 900
  • 11
  • 25
  • maybe i am understanding the "case" thing wrong? I see it kinda like a if statement. So even if i don't have a break after case 2 and the thing keep running, it doesn't meet the condition of case 3 and thus, shouldn't execute whatever is after case 3? – whales Oct 11 '15 at 20:45
  • You're right to think of it as an if statement in a way. But switch statement conditions are only checked once - and all it does is help you get to the right CASE. Conditions of an 'if' statement or an 'else if' statement are checked explicitly each time. That is why no break statement is necessary with an 'if' or 'else if' situation. So the thing to take away is that switch statements only check the condition once, and this merely helps the program get IN to the correct area, but not OUT. – Clint Oct 11 '15 at 20:48
  • yep. it's pretty much goto or jump. – ZhongYu Oct 11 '15 at 21:32