Manivel Sundaresan Manivel Sundaresan - 4 months ago 6
Java Question

Modification of value in switch case

public class Sample {
public static void main(String[] args) {
int i = 9;
switch (i) {
default:
System.out.println("default");
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
case 2:
System.out.println("two");
}
}
}


Output:

default
zero


Although
i
was initialized as 9, how is it possible that case 0 was picked? What is the reason?

Answer

You miss a break statement after the first default case so the excution just falls through to the second case.Also put the Default case last so that it is only excuted after all the other cases are checked.

 public static void main(String[] args) {
        int i = 9;
        switch (i) {

        case 0:
            System.out.println("zero");
            break;
        case 1:
            System.out.println("one");
            break;
        case 2:
            System.out.println("two");
            break;
        default:
            System.out.println("default");
            break;
        }
    }