4

A case falling through to the next case, may indicate an error, but sometimes it is intentional; if so, it is good practice to mark it so, for the benefit of both humans and the compiler.

The former can be done with a comment:

        switch (s.charAt(i)) {
        case '-':
            sign = true;
            // fallthru
        case '+':
            i++;
            break;
        }

I was hoping javac would notice the comment and be satisfied, but no, it still warns about fallthrough.

What's the recommended way to satisfy javac that this particular instance is intentional, while keeping the warning for the rest of the program?

rwallace
  • 31,405
  • 40
  • 123
  • 242

1 Answers1

0

If you are anyways going to execute the next case after the current case, then better would be to simply just combine the two cases into one... because the whole purpose of different cases is that they're non intersectional in nature.

  • 1
    Sometimes one case is a subset of the other; see above example. Of course that particular example would only involve duplicating one line of code, because I picked a very small one for readability here, but there can also be cases where the code duplication would be larger. – rwallace Oct 11 '19 at 09:59
  • In that case, the best option would be to have non intersectional cases, but if you want one case to fall into the other, then lets say the first case calls a method which then internally calls some other method which is also called in the next case. This would keep the cases non intersectional yet satisfy both the methods and give a view that one case falls into the other. – shreyas labhsetwar Oct 11 '19 at 10:03
  • 2
    It would be *an* option, to be sure. That ignoring the language feature provided for this exact purpose would be the *best* option, is an opinion with which I disagree. – rwallace Oct 11 '19 at 10:08