2

For the piece of code below, the 10 and 98 are printed out

int i = 10;
switch(i){
    default:
        System.out.println(100);
    case 10:
        System.out.println(10);
    case 98:
        System.out.println(98);
}

The thing I don't understand why the code in case 98 got execution while the case is not matching to compared value 10. To me, it is not very understandable. Can someone please explain to me?
Thank you very much.

Xitrum
  • 7,765
  • 26
  • 90
  • 126

1 Answers1

5

If you don't put a break at the end of each case, all the cases following the case that matches the value of i will be executed too.

switch(i){
    case 10:
        System.out.println(10);
        break;
    case 98:
        System.out.println(98);
        break;
    default:
        System.out.println(100);
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • should this be never happen ? since I don't understand the design point of java switch anymore ... – Xitrum Dec 10 '15 at 13:26
  • @TuanLD You put the default case first (note that I moved it to the end), so each value that is not 10 or 98 will result in all 3 cases being executed. – Eran Dec 10 '15 at 13:26