Java: How to check if object is null?

JavaAndroid

Java Problem Overview


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())?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

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!

Solution 4 - Java

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

Solution 5 - Java

DIY

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

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

Solution 6 - Java

drawable.equals(null)

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.

Solution 7 - Java

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

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

Solution 8 - Java

Just to give some ideas to oracle Java source developer :-)

The solution already exists in .Net and is more very more readable !

In Visual Basic .Net

Drawable drawable 
    = If(Common.getDrawableFromUrl(this, product.getMapPath())
        ,getRandomDrawable()
        )

In C#

Drawable drawable 
    = Common.getDrawableFromUrl(this, product.getMapPath() 
        ?? getRandomDrawable();

These solutions are powerful as Optional Java solution (default string is only evaluated if original value is null) without using lambda expression, just in adding a new operator.

Just to see quickly the difference with Java solution, I have added the 2 Java solutions

Using Optional in Java

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

Using { } in Java

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

Personally, I like VB.Net but I prefer ?? C# or if {} solution in Java ... and you ?

Solution 9 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNiko GamulinView Question on Stackoverflow
Solution 1 - JavaThomasView Answer on Stackoverflow
Solution 2 - JavadeamonView Answer on Stackoverflow
Solution 3 - JavaoutofcoffeeView Answer on Stackoverflow
Solution 4 - JavaheapuserView Answer on Stackoverflow
Solution 5 - JavaEdward J BeckettView Answer on Stackoverflow
Solution 6 - JavaAmitView Answer on Stackoverflow
Solution 7 - JavaBalaView Answer on Stackoverflow
Solution 8 - JavaschlebeView Answer on Stackoverflow
Solution 9 - JavaTom RView Answer on Stackoverflow