Java Data Type Tutorial - Java String Swtich








The switch-expression uses a String type. If the switch-expression is null, a NullPointerException is thrown.

The case labels must be String literals. We cannot use String variables in the case labels.

The following is an example of using a String in a switch statement.

public class Main {
  public static void main(String[] args) {
    String status = "off";
    switch (status) {
    case "on":
      System.out.println("Turn on"); 
    case "off":
      System.out.println("Turn off");
      break;// ww  w. j a v  a  2s.  c o  m
    default:
      System.out.println("Unknown command");
      break;
    }
  }
}

The code above generates the following result.





Switch Compare

The equals() method of the String class performs a case-sensitive string comparison.

public class Main {
  public static void main(String[] args) {
    operate("on");
    operate("off");
    operate("ON");
    operate("Nothing");
    operate("OFF");
    operate("No");
    operate("On");
    operate("OK");
    operate(null);//from  w  w  w.  java2 s  .c  om
    operate("Yes");
  }

  public static void operate(String status) {
    // Check for null
    if (status == null) {
      System.out.println("status  cannot be  null.");
      return;
    }
    status = status.toLowerCase();
    switch (status) {
    case "on":
      System.out.println("Turn on");
      break;
    case "off":
      System.out.println("Turn off");
      break;
    default:
      System.out.println("Unknown command");
      break;
    }
  }
}

The code above generates the following result.