null チェックと空チェックの組み合わせ
前のステップでは、==
演算子を使用して変数が null
かどうかをチェックする方法を学びました。しかし、Java では、特に String
オブジェクトを扱う際には、変数が null
かどうかだけでなく、「空」かどうかもチェックする必要があることがよくあります。空の文字列は、存在するが文字を含まない String
オブジェクトです(例:""
)。一方、null
の文字列は、変数が全く String
オブジェクトを参照していないことを意味します。
null
の文字列に対して isEmpty()
や length()
などのメソッドを呼び出そうとすると、NullPointerException
が発生します。したがって、null
の文字列と空の文字列を同じように扱いたい場合(例えば、「空白」または「欠落」と見なす場合)、両方の条件をチェックする必要があります。
これを行う最も一般的な方法は、まず文字列が null
かどうかをチェックし、null
でない場合に isEmpty()
メソッドを使用して空かどうかをチェックすることです。
これらのチェックを組み合わせる方法を実証するために、HelloJava.java
プログラムを修正してみましょう。
-
WebIDE エディタで HelloJava.java
ファイルを開きます。
-
現在のコードを次のコードに置き換えます。
public class HelloJava {
public static void main(String[] args) {
String text1 = null;
String text2 = ""; // An empty string
String text3 = "Hello"; // A non-empty string
System.out.println("Checking text1 (null):");
if (text1 == null || text1.isEmpty()) {
System.out.println("text1 is null or empty.");
} else {
System.out.println("text1 is not null and not empty: " + text1);
}
System.out.println("\nChecking text2 (empty):");
// It's crucial to check for null first!
if (text2 == null || text2.isEmpty()) {
System.out.println("text2 is null or empty.");
} else {
System.out.println("text2 is not null and not empty: " + text2);
}
System.out.println("\nChecking text3 (not empty):");
if (text3 == null || text3.isEmpty()) {
System.out.println("text3 is null or empty.");
} else {
System.out.println("text3 is not null and not empty: " + text3);
}
}
}
この更新されたコードでは、以下のことを行っています。
- 3 つの
String
変数を導入しています:text1
(null
)、text2
(空)、text3
(空でない)。
- 論理和演算子 (
||
) を使用して、null
チェック (text == null
) と空チェック (text.isEmpty()
) を組み合わせています。
- 条件
text == null || text.isEmpty()
は、text
が null
であるか、または text
が null
でなく、かつ text.isEmpty()
が true
の場合に true
になります。
- 重要:
||
条件では、null
チェック (text == null
) が最初に来る必要があります。もし text
が null
であれば、||
条件の最初の部分 (text == null
) が true
となり、Java は「短絡評価」を使用して 2 番目の部分 (text.isEmpty()
) をスキップするため、NullPointerException
を防ぐことができます。もし isEmpty()
チェックが最初に来て、text
が null
であれば、エラーが発生します。
-
ファイルを保存します(Ctrl+S または Cmd+S)。
-
ターミナルでプログラムをコンパイルします。
javac HelloJava.java
-
プログラムを実行します。
java HelloJava
次のような出力が表示されるはずです。
Checking text1 (null):
text1 is null or empty.
Checking text2 (empty):
text2 is null or empty.
Checking text3 (not empty):
text3 is not null and not empty: Hello
この出力は、組み合わせたチェックが null
の文字列 (text1
) と空の文字列 (text2
) を「null
または空」と正しく識別し、空でない文字列 (text3
) も正しく識別していることを示しています。
この組み合わせたチェック (string == null || string.isEmpty()
) は、null
の文字列と空の文字列を両方扱う必要がある場合の Java で非常に一般的なパターンです。多くのライブラリでもこのためのユーティリティメソッドを提供しています。例えば、Apache Commons Lang の StringUtils.isEmpty()
や StringUtils.isBlank()
(空白文字もチェックする)などですが、基本的な組み合わせチェックを理解することが基本です。