Java: How to check if object is null?

前端 未结 9 1512
甜味超标
甜味超标 2021-01-30 08:11

I am creating an application which retrieves images from the web. In case the image cannot be retrieved another local image should be used.

While trying to execute the f

9条回答
  •  北荒
    北荒 (楼主)
    2021-01-30 08:48

    I use this approach:

    if (null == drawable) {
      //do stuff
    } else {
      //other things
    }
    

    This way I find improves the readability of the line - as I read quickly through a source file I can see it's a null check.

    With regards to why you can't call .equals() on an object which may be null; if the object reference you have (namely 'drawable') is in fact null, it doesn't point to an object on the heap. This means there's no object on the heap on which the call to equals() can succeed.

    Best of luck!

提交回复
热议问题