== null と isEmpty() の違い
| 条件 | 意味 | 例 |
|---|---|---|
ImgFile == null |
そもそもオブジェクトが存在しない(未入力など) |
ImgFile が「無い」 |
ImgFile.isEmpty() |
オブジェクトはあるが中身が空 | 空のファイル、サイズ 0 のデータ |
NullPointerException(NPE)
null に対してメソッドを呼び出すと出されるエラー
AND
ex.java
if(ImgFile == null && ImgFile.isEmpty())return null
→ImgFile == nullが true でも、Java は AND(&&)式を最後までチェックしようとする
=ImgFile.isEmpty() が実行される
でもImgFileはnullなのでnullに対してisEmpty()を呼び出すとNPE
OR
ex.java
if(ImgFile == null || ImgFile.isEmpty())return null
- Java の OR(||)にはショートサーキット効果がある
→左が true の場合 → 右は評価しない
つまり、 - ImgFile == null → true → 右側(isEmpty)は評価しない → NPE 出ない
- ImgFile != null の時 → isEmpty を評価 → OK