0

The following is the code i used in a program - over here the month variable is an integer

  switch(month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
  return 31;
  break;
case 2:
  return 28;
  break;
case 4:
case 6:
case 9:
case 11:
        return 30;
  break;
default:
  System.out.println("Invalid month.");
  return 0;
}

surprisingly, when i use the above switch construct.. it gives an error saying.. code unreachable for statements after each break statement

Then i removed all the break statements, and the new code looks like this ---

  switch(month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
  return 31;

case 2:
  return 28;

case 4:
case 6:
case 9:
case 11:
        return 30;

default:
  System.out.println("Invalid month.");
  return 0;
}

Now.. after removing the break statements .. the code worked perfectly well..

My question is... in the switch construct.. it is mandatory to use break.. or else the control flow will be continued.. and all the conditions are tested and executed!! right???

So why in the world is the previous ** syntactically Right** version giving an error.. and the modified syntactically incorrect version running perfectly well..

Any explanation.. anyone!!

nav
  • 21
  • 3
  • 1
    http://stackoverflow.com/questions/2545110/find-the-number-of-days-in-a-month-in-java – Michael Brewer-Davis Jun 26 '11 at 02:26
  • just so that there's no confusion, it is **not** syntactically incorrect to not use break statements in a switch, it is allowed, and should generally compile without error. –  Jun 26 '11 at 02:29

5 Answers5

2

Because code stops executing when you use "return".

Snowy Coder Girl
  • 5,408
  • 10
  • 41
  • 72
  • You only use "breaks" in order to prevent the rest of the "case"s from running. But since you "return", there is no way for anything else in the method to be run. – Snowy Coder Girl Jun 26 '11 at 01:37
  • 1
    See this, it will help explain. They show cases where they don't use breaks and explain what happens: http://download.oracle.com/javase/tutorial/java/nutsandbolts/switch.html – Snowy Coder Girl Jun 26 '11 at 01:41
1

The error message is telling you that the break statements will never be executed, because they always follow a return statement.

It is not mandatory to use break statements in a switch construct.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
1

You don't need the break because you already have return. If you return then you'll never reach the break, which is why you get the error.

Peter Alexander
  • 53,344
  • 14
  • 119
  • 168
0

return exits the loop entirely, making break unreachable.

Keelx
  • 907
  • 3
  • 17
  • 26
0

break is not compulsary in the switch satatement. ic case you use a return statement it ill not be required.

siddhant
  • 15
  • 5