Use string literals in switch statements in Java

Description

The following code shows how to use string literals in switch statements.

Example


/*from   w  w  w  .  j  a  v  a  2  s . c o m*/
public class Main {
  public static void main(String[] args) {
    String[] data = new String[]{"a","b","java2s.com"};
    for (String argument : data) {
      switch (argument) {
      case "a":
      case "b":
        System.out.println("a or b");
        break;
      case "java2s.com":
        System.out.println("java2s.com");
        break;
      case "-help":
        System.out.println("displayHelp");
        break;
      default:
        System.out.println("Illegal command line argument");
      }

    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures