-1
public class Demo {
    public static void main(String args[]) {
        char c = 'A' ;
        int num = 10 ;

        switch(c) {
            case 'B' :
                num++ ;
            case 'A' :
                num++ ;
            case 'Y' :
                num++ ;
                break ;
            default :
                num-- ;
        }

        System.out.println(num);
    }
}

I think the program will passed case 'A' so the num will be 11. I ran it in Idea and saw that the program passed case 'A' and case 'Y'(???). Finally, the num is 12.

I try this: System.out.println('A' == 'Y'); and it returnfalse

Filburt
  • 17,626
  • 12
  • 64
  • 115

1 Answers1

0

In the example the program first passes case 'A' since the char in c is A, but then it "falls through" to case 'Y' since case 'A' does not end with a break.

If this behaviour is not desired, add a break to case 'A'.

Read https://medium.com/swlh/understanding-switch-case-fall-through-in-java-70b448427b0a for more details.

Petra Minaler
  • 91
  • 1
  • 8
  • Ah, I remember, there would be a break after each case, which was a trap deliberately left by the title.Thanks. – Franz Kafka Jun 14 '23 at 07:24