Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if object is null or not except == null

Tags:

java

null

I want to make method that will check if the class instance is null or not.

Simply I know that i can use == null, but I want to know that is there any other way that can be implemented to check if instance is null or not ?

I have nearly 70-80 class instance. & all that class extend same Class BaseEntity.

at time of declaration I have declare each instance like :

Entity1 instance1 = null;

like so I have defined all 70 class instances.

when they will be used I am initializing them using new. but at end of my main Entity Processor, I have to store data of each Entity id it is initialized, so for that I ll have to check if instance is null or not ?

All Entities extend same class BaseEntity so I have made following method.

I know only one method :

public boolean checkIfEntityNull(BaseEntity entity){
        return  entity != null ? true : false;
}

if it returns true then I ll call it's save method of repository to save data in DB otherwise it ll not call save method.

So any guidance on it guys.

like image 789
user3145373 ツ Avatar asked Sep 03 '14 10:09

user3145373 ツ


People also ask

Can you use == for null?

equals(null) will always be false. The program uses the equals() method to compare an object with null . This comparison will always return false, since the object is not null .

Which is better null != Object or object != null?

The first two are equivalent, but the "null != object" is an old practice from languages where it is valid to write "if (object = null)" and accidentally assign null to the object. It is a guard to stop this accident from happening.

IS null == null true in Java?

Summary. undefined is a primitive type of a variable which evaluates falsy, has a typeof() of undefined, and represents a variable that is declared but missing an initial value. null == undefined evaluates as true because they are loosely equal.


1 Answers

The easiest way to check is entity == null. There is no shorter way to do that.

Note that there is a method for this in the standard lib:

Objects.isNull(Object obj)

And another one which is the opposite of the above one:

Objects.nonNull(Object obj)

And there is yet another one which can be used to force a value to be not null, it throws a NullPointerException otherwise:

T Objects.requireNonNull(T obj);

Note: The Objects class was added in Java 7, but the isNull() and nonNull() methods were added only in Java 8.

like image 196
icza Avatar answered Oct 24 '22 02:10

icza