Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java program problem: Unexpected value num

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading