3

I'm new to Java and am learning switch statements. However, the wrong case (case "two") seems to be matched. I suspect that it's because of the lack of break; after case "one", but can someone please explain to me the logic behind Java switch statements? Why is case "two" matched at all when the values don't even match?

Here is my code:

String a = "one";
switch(a) {
    case "one": System.out.println("a is one");
    case "two": System.out.println("a is two");
    default: System.out.println("numbers");
}

I expected output:

a is one
numbers

But got:

a is one
a is two
numbers

Jon
  • 33
  • 4

4 Answers4

3

The case statement is evaluated from top to bottom, when it finds a match it will enter at that point and continue downwards until a break is found (or it gets to the bottom without finding a match). You cannot drop into "one", skip over "two" and re-enter a default.

Default is used when none of the other cases above it match

Jimmy
  • 16,123
  • 39
  • 133
  • 213
1

You need break statements

    String a = "one";
    switch(a) {
        case "one": System.out.println("a is one"); break;
        case "two": System.out.println("a is two"); break;
        default: //
    }
    System.out.println("numbers")

Then maybe print the numbers afterward

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. 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.

If all the cases has been checked and not passed then default case will be executed. Thus in your case the code should be like this.

String a = "one";
switch(a) {

    case "one":
        System.out.println("a is one");
        break;

    case "two": 
        System.out.println("a is two");
        break

    default: 
        System.out.println("None of the cases matched ");
}

System.out.println("numbers");
Sarangan
  • 868
  • 1
  • 8
  • 24
0

In switch statement, the value of the expression is compared with each of the literal values in the case statements. If a match is found l, the code sequence following the case is executed. However, the default statement is optional. The break statement is used inside the switch to terminate a statement sequence. When a break statement is encountered, execution branches to the first of code that follows the entireswitch statement. This has the effect of jumping out of the switch. If you omit the break execution will continue on into the next case.