0
0

【備忘録】switch文で文字列を条件にする時

Posted at

皆さんはswitch文よく書きますか?

私は条件分岐が大量になるとき以外はif文で書くのことが多いんですが、どっちの方が良いんでしょうね。

さて、今回はswitch文で文字列を条件にする時の注意点についてまとめていこうと思います。

注意点

以下の様に、switch文を書いたとします。
String str = ""; //任意の文字列

switch (str) {
case string1 :
    //ここに処理内容
    break;

default :
    //ここに処理内容
    break;
}

こんな感じですね。

ここで注意しないといけないのが、条件にしてる文字列strnullの場合です。

String str = null;

switch (str) {
case string1 :
    //ここに処理内容
    break;

default :
    //ここに処理内容
    break;
}

この場合、一見デフォルトの条件に入るように見えるんですが、NullPointerExceptionになります。

そもそもJava7以降からでしか、文字列をswitch文で扱えないそうです。

対応方法

nullチェックを行い、空文字を代入し直せばエラーを回避することが出来ます。
String str = null;

if (str == null) {
    str = ""; //ここで空文字を代入しておく。
}

switch (str) {
case string1 :
    //ここに処理内容
    break;

default :
    //ここに処理内容
    break;
}
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0