enter image description here

I don’t understand where 6 came from, I thought it would be 2, that's why I’m filling up the interviews. I wonder why there are 6, not 2?

  • 2
    because there is no break; - Alexey Shimansky
  • 2
    In order not to get cons, try to formulate a question better and not to give the code in the form of a screenshot. - Yuriy SPb
  • Frankly speaking, I also always wonder why in such cases it fails in case 1: when s already 2 . It would be clearer if the swich operator would be replaced with some goto - go to the label and further code execution after the label. In fact, because it is so. - Igor Kudryashov

2 answers 2

Your arguments forget that there is no break , and in this case the case “fails”. That is, roughly speaking, the compiler sees this code differently, somewhere like that

 i = 0; s = 0; s+=2; i+=s; s+=2; i+=s; 

The correct answer to this question would be - there is no break , this is bad code.

  • 7
    If there is no break it doesn’t mean that the code is bad) There are situations when it is intentionally lowered, so that it will fail further - Alexey Shimansky
  • one
    Yes, there are tricks when it is lowered. And one of such cases is when there are several cases in a row. And this is normal (just in java6 there is no possibility in the case of writing a range). But the similar code in the example is an example of bad code. - KoVadim
  • @KoVadim the correct answer is "6", and not "this is a bad code" :-) - cache
  • one
    I was asked a similar question at the interview. I asked - do you write all the code like that? Then it was fun. - KoVadim

Because after the first case there is no break statement (or another interrupt statement), respectively, the program execution proceeds to the next case .