Java - switch statement vs if statement

Introduction

A switch statement is a clearer way of writing an if-else statement if the condition-expression in an if statement compares the same variable.

For example, the following if-else and switch statements accomplish the same thing:

Demo

public class Main {
  public static void main(String[] args) {
    int i= 10;/*  w  ww .ja  va  2 s  .  c  om*/
    // Using an if-else statement
    
    if (i == 10)
      System.out.println("i is 10");
    else if (i == 20)
      System.out.println("i is 20");
    else
      System.out.println("i is neither 10 nor 20");

    // Using a switch statement
    switch (i) {
    case 10:
      System.out.println("i is 10");
      break;
    case 20:
      System.out.println("i is 20");
      break;
    default:
      System.out.println("i is neither 10 nor 20");
    }
  }
}

Result

Related Topic