How to check if object is null or not other than == null

I want to create a method that will check if an instance of a class is null or not.

It's just that I know I can use it == null

, but I want to know if there is another way that can be implemented to check if an instance is null or not?

I have an instance of a class 70-80

. and this whole class extends the same class BaseEntity

.

during declaration, I declare each instance, for example:

Entity1 instance1 = null;

so I defined everything 70 class instances

.

when they are used I initialize them with new. but at the end of my main one Entity Processor

, I have to store the data of each Entity it is initialized, so for that I need to check if the instance is null or not?

All Entities extend

the same class BaseEntity

, so I made the following method.

I only know one method:

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

      

if it returns true

then I'll call it save method of repository to save data in DB

, otherwise it won't call the save method.

So any advice on this guys.

+3


source to share


1 answer


The easiest way to check: entity == null

. There is no shorter way to do this.

Note that there is a method in the standard lib:

Objects.isNull (object obj)

And one more, opposite to the above:



Objects.nonNull (Object obj)

And there is another way that can be used to ensure that the value is not null

, it throws out NullPointerException

otherwise:

T Objects.requireNonNull (T obj);

Note. Class Objects was added in Java 7, but isNull()

and nonNull()

were added only in Java 8.

+4


source







All Articles