どうも、ちょげ(@chogetarou)です。
文字列(string)が空文字(“”)もしくはnullかどうか判定する方法を紹介します。
方法

文字列(string)が空文字(“”)もしくはnullかどうか判定するには、「||」とisEmpty()を使います。
まず、「||
」の左辺に「str == null」(str=対象の文字列)を指定します。
そして、「||
」の右辺に文字列から呼び出したisEmpty()の結果を指定します。
text == null || text.isEmpty()
上記の条件式は、文字列が空文字もしくはnullならば「true」、空文字でもnullでもなければ「false」を返します。
使用例
public class Main {
public static void main(String[] args) throws Exception {
String text = "";
String text2 = "Hello";
String text3= null;
System.out.println(checkEmpty(text));
System.out.println(checkEmpty(text2));
System.out.println(checkEmpty(text3));
}
private static boolean checkEmpty(String text) {
return text == null || text.isEmpty();
}
}
出力:
true
false
true
コメント