Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to check if object is null?

Tags:

java

android

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

like image 942
Niko Gamulin Avatar asked Jan 09 '10 10:01

Niko Gamulin


People also ask

How do you check if an object is not null?

), also known as the strict equality operator, to be sure that the value in question is definitely not null: object !== null . That code checks that the variable object does not have the value null . Some developers prefer the double equality operator ( == or !=

When an object is null in Java?

According to the Java spec, null is a type that can be assigned to an object variable (as a value as noted in the comment). You cannot instantiate or create variables of this type though, you must use the literal null provided by the compiler.

How do you check if a date object is null?

Check if it is null: if (date == null) {...} Check if it is not null: if (date !=

IS null == null in Java?

out. println("(Object)string == number: " + ((Object)string == number)); To conclude this post and answer the titular question Does null equal null in Java? the answer is a simple yes.


2 Answers

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.

like image 89
Thomas Avatar answered Sep 20 '22 06:09

Thomas


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.

like image 22
deamon Avatar answered Sep 20 '22 06:09

deamon