Switch Expressions in Java 12

Java is a wonderful language, but it’s syntax tends to be a bit too verbose sometimes. It is good to see that in Java 12, the new Switch Expressions will now use pattern matching to provide simpler coding standards.

Below is a simple example to illustrate the differences:

In Java 11

int numLetters;

switch (fruit) {
  case PEAR:
    numLetters = 4;
    break;
  case APPLE:
  case GRAPE:
  case MANGO:
    numLetters = 5;
    break;
  case CHERRY:
  case ORANGE:
  case PAPAYA:
  case BANANA:
    numLetters = 6;
    break;
  case WATERMELON:
  case GRAPEFRUIT:
    numLetters = 10;
    break;
  default:
    numLetters = 0;
}

Now in Java 12

int numLetters = switch (fruit){
   case PEAR -> 4;
   case APPLE, MANGO, GRAPE -> 5;
   case ORANGE, PAPAYA, BANANA -> 6;
   case WATERMELON, GRAPEFRUIT -> 10;
   default -> numLetters = 0;
}

As you can see, this new switch expression brings clearer and cleaner code.

188 total views, 2 views today

No Comments

Post a Comment