switch文の文字列

JDK 7リリースでは、switch文の式にStringオブジェクトを使用できます。

public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
     String typeOfDay;
     switch (dayOfWeekArg) {
         case "Monday":
             typeOfDay = "Start of work week";
             break;
         case "Tuesday":
         case "Wednesday":
         case "Thursday":
             typeOfDay = "Midweek";
             break;
         case "Friday":
             typeOfDay = "End of work week";
             break;
         case "Saturday":
         case "Sunday":
             typeOfDay = "Weekend";
             break;
         default:
             throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
     }
     return typeOfDay;
}

switch文では、その式内のStringオブジェクトが、各caseラベルの式と比較されます。String.equalsメソッドを使用した場合と同様の比較が行われるため、結果として、switch文のStringオブジェクトの比較では大文字と小文字が区別されます。通常、Javaコンパイラで生成されるバイト・コードの効率は、Stringオブジェクトを使用するswitch文の方が、一連のif-then-else文よりも高くなります。


Copyright © 1993, 2020, Oracle and/or its affiliates. All rights reserved.