0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

nullチェック

Posted at

== 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
0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?