Java Switch

The Java switch

  • The switch can be used to resolve data types such as int, char, byte, and char.
  • From JDK 7 onwards, the switch statement supports resolving Strings too.
  • So the syntax of the switch statement will look like below.

int type = 3;

switch (type) {
    case 1:
        System.out.println("The type is 1");
        break;
    case 2:
        System.out.println("The type is 2");
        break;
    case 3:
        System.out.println("The type is 3");
        break;
    default:
        System.out.println("Type not found");
}
    
  • Now let’s talk about the anatomy of the switch statement.

The syntax of the switch statement

  • As you can see above, the syntax of the switch statement consists of several key parts.
  • First the variable that need to be compared is expressed as below,

switch (type)
    
  • Next the cases and code that need to run are kept inside curly brackets.
The ‘case’ statement

int type = 3;

switch (type) {
    case 1:
        System.out.println("The type is 1");
        break;
    case 2:
        System.out.println("The type is 2");
        break;
    case 3:
        System.out.println("The type is 3");
        break;
    default:
        System.out.println("Type not found");
}
    
  • Each case statement must have a unique constant expression.
  • Followed by a colon after ‘case’ and the constant value, the code that needs to run if the constant matches the variable is kept.
  • At the end of each case, a break statement is required.

    case "a":
        System.out.println("Hello from case 'a'");
        break;
    
The ‘break’ statement
  • The ‘break’ statement marks the end of each case to terminate the statement sequence.
  • So the ‘break’ statement is there to stop executing the rest of the code inside the switch.
  • The ‘break’ statement effectively stops executing code inside the ‘switch’ and jumps out of the switch.

    case "a":
        System.out.println("Hello from case 'a'");
        break;
    
  • ⚠️ If the ‘break’ statement is omitted, it will continue to execute into the next case, and each case will be executed until a break statement or the end of the switch.
The ‘default’ statement
  • Finally the ‘default’ statement is there to run if there is no matching case for the given variable.

    default:
        System.out.println("Invalid");
    

The “break” statement is there to jump out of the switch.

Pages: 1 2 3