Unable to get behaviour of Switch case in java

后端 未结 8 719
迷失自我
迷失自我 2021-01-23 14:07

I have written small code in java 6

public class TestSwitch{

public static void main(String... args){
    int a = 1;
    System.out.println("start");
          


        
相关标签:
8条回答
  • 2021-01-23 14:44
     See if a=1 then your case 1 will work then 1 will pe printed if as we have not using      break after case 1 so all cases are working in flow so output is coming like this if you want to execute only one case at one time then you have to put break after one case like
    
    switch(a){
            case 1:
                System.out.println(1);
                 break;
                case 3:
                    System.out.println(3);
                 break;
                case 4:
                    System.out.println(4);
                 break;
    

    Then it will break out of the switch case on encountering break statement

    0 讨论(0)
  • 2021-01-23 14:53

    Your code will give compilation errors as we can't use curly brace after case : Exact code is:

    public static void main(String... args){
            int a = 1;
            System.out.println("start");
            switch(a){
                case 1:
                    System.out.println(1);
                    case 3:
                        System.out.println(3);
                    case 4:
                        System.out.println(4);
    
                case 2:
                    System.out.println(2);
                    case 5:
                        System.out.println(5);
                    case 7:
                        System.out.println(7);
                }
    
            System.out.println("end");
        }
        }
    

    and output will be start 1 3 4 2 5 7 end because you have not use "break" after each case.

    0 讨论(0)
提交回复
热议问题