FreeCode

Donate HTML/CSS JavaFX Java Home
Array Data Structures Array List Data Structures Linked List Data Structures Stack Data Structures Queue Data Structures While Loops Do-While Loops For Loops For-each Loops If, Else, and Multi-Way If Statements Switch Statements Try-Catch Blocks Comment Types and Javadoc Java Classes Java Methods

Switch Statements

Code Description:

Switch statements can be used instead of Multi-Way If Statements when the statements that can execute depend on the value of one variable or the result of a mathematical expression.

Switch Statement Syntax:

int key = 2;
		
switch (key) {

case 1:
    // Do stuff here	    
    break;
case 2:
    // Do stuff here
    break;
default:
    // Do stuff here if the other cases were not executed
    break;
}

Runnable Switch Statement Example Code:

public class Demo {

    public static void main(String[] args) {
		
	int key = 2;
		
	switch (key) {

	case 1:
            System.out.println("Case 1 was executed");
	    break;
	case 2:
	    System.out.println("Case 2 was executed");
	    break;
	case 3:
	    System.out.println("Case 3 was executed");
	    break;
	case 4:
	    System.out.println("Case 4 was executed");
	    break;
	case 5:
	    System.out.println("Case 5 was executed");
	    break;
	default:
	    System.out.println("No cases matched the key so the default was executed");
	    break;
	}
		
    }

}

How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.

Output:

Switch Statement Output Image

Important Notes:

  • The variable or switch expression result can only be of data types char, byte, short, int, and String.
  • "break" statements immediately terminate the switch statement's execution.
  • "break" statements should be used after every case, excluding the default case, to prevent the statements in multiple cases from being executed.
  • The "default" case is used to execute statements if none of the other cases were executed.
  • The "default" case should be the last case in a switch statement.
  • "default" cases and "break" statements are optional.

Related Links:

If, Else, and Multi-Way If Statements