The following article describes the Purpose of Using default Keyword in a switch Statement in Java.

In order to specify the default behavior, we use the break statement within a switch statement. Furthermore, this default behavior carries out only when none of the case labels match the value in the switch statement.

The following code example shows how the default keyword can be used in a switch statement.

int day = 4;
switch (day) {
   case 1:
      System.out.println("Monday");
      break;
   case 2:
      System.out.println("Tuesday");
      break;
   case 3:
      System.out.println("Wednesday");
      break;
   default:
      System.out.println("Other day");
}

In this example, the value of the day variable is 4, which does not match any of the case labels. Therefore, the code inside the default block will be executed and the following will be printed to the console.

Output

Other day

The default case is optional in a switch statement. However, it is often a good idea to include a default case in your switch statements to handle unexpected input or provide a default behavior.



Further Reading

Java Practice Exercise

programmingempire

Princites