Java Tutorial Java Advanced Java References

Java default Keyword



The Java default keyword is used to build a block of code in the switch statement and the default block of code is evaluated when no case matches with the switch expression.

Syntax

switch (expression){
  case 1:
     statement 1;
     break;
  case 2:
     statement 2;
     break;
     ...
     ...
     ...
  case N:
     statement N;
     break;
  default:
     default statement;
} 

Example:

In the example below, the switch expression is a variable called i with value 10 which is matched against case values. As there is no case that matches with value 10, hence default block of code gets executed.

public class MyClass {
  public static void main(String[] args) {
    int i = 10;
    switch(i){
      case 1: 
         System.out.println("Red");
         break; 
      case 2: 
         System.out.println("Blue");
         break;
      case 3: 
         System.out.println("Green");
         break;
      default:
         System.out.println("There is no match in the switch statement.");
    }  
  }
}

The output of the above code will be:

There is no match in the switch statement.

❮ Java Keywords

5