0

In the below code when i comment the breaks,when i write a case(say "start") it will print all the cases output below,means all the three lines are printed,when i write "stop" it prints two output "Mechine stopped" and "No command given",why do i need to give break statement as the compiler searches for the cases,if matches then print the related output.

    import java.util.Scanner;
    public class App{
    public static void main(String args[]){
    Scanner input = new Scanner(System.in);
    String text = input.nextLine();
    switch(text){
        case "start":
        System.out.println("Mechine Started");
        break;
        case "stop":
        System.out.println("Mechine stopped");
        break;
        default:
        System.out.println("No command given");


            }
        }
    }
  • Side note, in general you will want to further indent the code under each case, as if they were surrounded by curly braces – Hill May 24 '16 at 16:31

3 Answers3

6

why do i need to give break statement as the compiler searches for the cases,if matches then print the related output.

Because that's how it's defined to work. Your program will fall-through the remaining case clauses unless you explicitly break

See the JLS section 14.11 and note:

If one of the case constants is equal to the value of the expression, then we say that the case matches, and all statements after the matching case label in the switch block, if any, are executed in sequence.

It's similar to the switch behaviour in C, note. From Wikipedia:

Languages derived from C, and more generally those influenced by Fortran's computed GOTO, instead feature fallthrough, where control moves to the matching case, and then execution continues ("falls through") to the statements associated with the next case in the source text

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

Fall through

Another point of interest is the break statement. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

Without using break in switch statement is fall-through logic

switch statement did not say "You need to include break".

Best practice is that you should add comment //fall-through when you used this logic.

Necromancer
  • 869
  • 2
  • 9
  • 25