switch statemt functioning improperly and giving error when i put break;

Posted by nav on Stack Overflow See other posts from Stack Overflow or by nav
Published on 2011-06-26T01:31:50Z Indexed on 2011/06/26 8:22 UTC
Read the original article Hit count: 155

Filed under:

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 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!!

© Stack Overflow or respective owner

Related posts about java