-2

A switch statement is basically a if, elif, elif, elif, elif, else.

Why does a switch statement need a break within it and an else if statement doesnt? What is the difference?

If, else if doesn't require a break.

if (c = 'a'){
     System.out.println("");
}
else if (c = 'b'){
     System.out.println("");
}

Switch statement requires a break.

switch(c){
case('a'){
     System.out.println("");
     break;}
case('b'){
     System.out.println("");
      break;}
}
Eduardo Morales
  • 764
  • 7
  • 29
  • 4
    You forgot to use`break;` in each case. See [Strings in switch Statements](http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html) – asdf Oct 29 '16 at 00:13
  • Possible duplicate of [Switch without break](http://stackoverflow.com/questions/8563970/switch-without-break) – DimaSan Oct 29 '16 at 08:03

1 Answers1

3

You have to add break to each case, e.g.

switch(choice){
   case 1:
     System.out.print("haha");
     break;
   case 2:
     System.out.print("aloha");  
     break;
}

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.

Jim Lewis
  • 43,505
  • 7
  • 82
  • 96
Ján Яabčan
  • 743
  • 2
  • 10
  • 20