Home > Blockchain >  Why is the second line after the first is being printed even though the two don't match?
Why is the second line after the first is being printed even though the two don't match?

Time:12-19

I am learning simple switch case usage in java in particular

public class HelloWorld {
    public static void main(String args[]) {
        int k = 2;
        switch (k) {
        case 'a':
            System.out.println("Welcome");
        case 2:
            System.out.println("To");
        case 'b':
            System.out.println("Infosys");
            break;
        default:
            System.out.println("Hello");
        }
    }
}

I want to understand why the output of the above code is coming out to be "To Infosys" and not "To Hello". I know that the break is not there, even then the second case being of 'b' is not matching. Why the printing of "Infosys" when the case is not matched?

CodePudding user response:

You can find an answer in the Oracle documentation for switch-case "Without break all statements after the matching case label are executed in sequence regardless of the expression of subsequent case labels"

Default was not executed because of the "break" in 'b' case.

CodePudding user response:

From the documentation of switch statement:

The switch statement evaluates its expression, then executes all statements that follow the matching case label.

The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered

In your example, as the matching case label is 2, all statements following this case are executed. Thus your program should print "To Infosys Hello" But as you have a break; in case 'b', so your program is printing "To Infosys" only.

  • Related