Java: How to check if object is null?

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 following lines:

Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (drawable.equals(null)) {
  drawable = getRandomDrawable();

The line if(drawable.equals(null)) throws an exception if drawable is null.

Does anyone know how should the value of drawable be checked in order not to throw an exception in case it is null and retrieve the local image (execute drawable = getRandomDrawable())?

Asked by: Owen842 | Posted: 24-01-2022

Answer 1

Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (drawable == null) {
    drawable = getRandomDrawable();

The equals() method checks for value equality, which means that it compares the contents of two objects. Since null is not an object, this crashes when trying to compare the contents of your object to the contents of null.

The == operator checks for reference equality, which means that it looks whether the two objects are actually the very same object. This does not require the objects to actually exist; two nonexistent objects (null references) are also equal.

Answered by: Aida693 | Posted: 25-02-2022

Answer 2

Edited Java 8 Solution:

final Drawable drawable = 
    Optional.ofNullable(Common.getDrawableFromUrl(this, product.getMapPath()))
        .orElseGet(() -> getRandomDrawable());

You can declare drawable final in this case.

As Chasmo pointed out, Android doesn't support Java 8 at the moment. So this solution is only possible in other contexts.

Answered by: Rebecca643 | Posted: 25-02-2022

Answer 3

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!

Answered by: Justin815 | Posted: 25-02-2022

Answer 4


private boolean isNull(Object obj) {
    return obj == null;

Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (isNull(drawable)) {
    drawable = getRandomDrawable();

Answered by: Michelle505 | Posted: 25-02-2022

Answer 5

if (yourObject instanceof yourClassName) will evaluate to false if yourObject is null.

Answered by: Arthur803 | Posted: 25-02-2022

Answer 6


The above line calls the "equals(...)" method on the drawable object.

So, when drawable is not null and it is a real object, then all goes well as calling the "equals(null)" method will return "false"

But when "drawable" is null, then it means calling the "equals(...)" method on null object, means calling a method on an object that doesn't exist so it throws "NullPointerException"

To check whether an object exists and it is not null, use the following

if(drawable == null) {

In above condition, we are checking that the reference variable "drawable" is null or contains some value (reference to its object) so it won't throw exception in case drawable is null as checking

null == null

is valid.

Answered by: Chelsea508 | Posted: 25-02-2022

Answer 7

Use google guava libs to handle is-null-check (deamon's update)

Drawable drawable = Optional.of(Common.getDrawableFromUrl(this, product.getMapPath())).or(getRandomDrawable());

Answered by: Lydia759 | Posted: 25-02-2022

Answer 8

It's probably slightly more efficient to catch a NullPointerException. The above methods mean that the runtime is checking for null pointers twice.

Answered by: Arthur173 | Posted: 25-02-2022

Similar questions

android - digital compass problem

I am creating an augmented reality application and I noticed that the stored locations don't appear appear on the correct direction if I try to use the camera view (using layar or wikitude API). The problem is that the digital compass doesn't show north correctly when you try to look at the known objects through the camera view. If align the phone with the ground (look at my shoes) the locations appear at the screen accord...

android - How to remove labels from a MapView?

I am trying to make a satellite view (via a MapView) without labels. How can I do this?

android - Custom title with image

i'm creating custom title for activity by disabling standard one and managing everything myself. I wonder if it's possible to replace/theme standart title to my needs. I can customize size, background image, and text via themes by changing windowXYZStyle items. The only thing i couldn't find - how i can add image instead of text. I've tried requestWindowFeature(Window.FEATURE_CUSTOM_TITLE) and ...

canvas - Android draw with blur

I need do draw on Android's Canvas using Blur effect, it is a very simple feature, I need to draw a circular area, which is blurred (the foreground) and the background transparent, I can do everything with manipulating the colour alpha to do it with custom transparency but I need it to be blurred instead of transparent.. any ideas?

layout - How to resize a android webview after adding data in it

In a layout (linear, vertical) hierarchy I've got several views and one of them is a WebView. They all have same parameters: android:layout_width="fill_parent" android:layout_height="wrap_content" For all views, the spacing between elements is correctly handled but for the Webview there is a lot of spaces after the displayed text inside. I set the (HTML) text of the webview in the ...

How to find easily the source of an android class

I know I can access android source code from, but it's hard to select the right git repo if I only know the package and the name of an android class. Isn't there a way to locate a file in

camera - Android Intent Save Path

At the moment I am using two intents. One for voice-recording, another for the camera: Intent photoIntent = new Intent(""); startActivityForResult(photoIntent, ACTIVITY_TAKE_PHOTO); Intent voiceIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION); startActivityForResult(voiceIntent, ACTIVITY_RECORD_SOUND); My aim is to put an Extra to each of t...

Android "hover" event in custom layout

I have a custom layout that I have written that basically just displays a bunch of ImageViews. I am handing onTouch events for all the ImageViews in my layout. However, if a user touches one imageView and then drags over another ImageView, I would like to be able to handle that as well. How would I go about capturing this behaviour?

android - What is the ideal place to cache images?

I am fetching a lot of thumbnails in my application from a remote server and lazy-loading these in a list view. The image fetches run in a background AsynTask and when completed the fetched images are stored in a HashMap using SoftReferences. This works just fine but when the images in the cache gets GC’d, the fetches have to be rerun. I could have stored them on the SD card so there would be no...

How to create a tree view in Android?

There are no controls in Android that provide Tree-like View. There is an ExpandableList View which I suspect could be used to creating one. Have you tried imlpementing such a control? How would one implement such a control in Android?

Still can't find your answer? Check out these communities...

Android Google Support | Android Community | Android Community (Facebook) | Android