Monday, December 8, 2014

Strings in switch Statements - available from Java 7 on

Good to know - Java 7 supports String type in switch statement.

Note 1: String are compared via equals() method - note, not via equalsIgnoreCase! and not via  ==.
Note 2: switch argument must not be null - else  NullPointerException is thrown.

Example code:
        String color = "#0000FF";
        color = color.toLowerCase();
        switch (color) {
          case "#0000ff":
              System.out.println("BLUE");
          break;
          case "#ff0000":
              System.out.println("RED");
          break;
          default:
              System.out.println("INVALID COLOR CODE");
        }

More: Oracle info on the topic.