【Java】nullチェック

Nullチェック

isNull/nonNull

※nonNullは結果が逆になる
Java 8以降のみ

Objects.isNull(hoge)
Objects.nonNull(hoge)
結果
null true
"" false
" " false
" " false
==null/!=null

※!=nullは結果が逆になる

String hoge = null;
if (hoge == null){
    System.out.print("nullです");
}

空文字チェック

isEmpty

※Stringクラスのメソッド

String hoge = "";
hoge.isEmpty
結果
null false
"" true
" " false
" " false
==""/!=""

※!=""は結果が逆になる

String hoge = "";
if (hoge == ""){
    System.out.print("空文字です");
}

空文字+空白チェック

isBlank

※Stringクラスのメソッド
Java 11以降のみ

String hoge = "";
hoge.isBlank
結果
null false
"" true
" " true
" " true

Null+空文字チェック

isEmpty/isNotEmpty

※org.apache.commons.lang.StringUtilsのインポート必要
※isNotEmptyは結果が逆になる

StringUtils.isEmpty(hoge)
StringUtils.isNotEmpty(hoge)
結果
null true
"" true
" " false
" " false

Null+空文字+空白チェック

isBlank/isNotBlank

※org.apache.commons.lang.StringUtilsのインポート必要
※isNotBlankは結果が逆になる

StringUtils.isBlank(hoge)
StringUtils.isNotBlank(hoge)
結果
null true
"" true
" " true
" " true