Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check not null in Java

Tags:

java

notnull

Imagine I have, say, XML-generated entity in Java that holds some data I need. For example:

<Car>
   <Engine>
      <Power>
         175
      </Power>
   </Engine>
</Car>

So if I need an engine power, I, followed by the best practices of business software development, will do the next thing:

Car car = dao.getCar()
Power power = car != null && car.engine != null ? power : null
return power

I hate this. Sometimes it seems that half of the code is just null checks.

Any ideas?

like image 531
Andrei Zhaleznichenka Avatar asked Sep 08 '17 11:09

Andrei Zhaleznichenka


People also ask

How do you check it is not null?

The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

Can you == null in Java?

== and !=The comparison and not equal to operators are allowed with null in Java. This can made useful in checking of null with objects in java.

IS null == null in Java?

To conclude this post and answer the titular question Does null equal null in Java? the answer is a simple yes.

Does isEmpty check for null Java?

isEmpty(< string >)​ Checks if the <string> value is an empty string containing no characters or whitespace. Returns true if the string is null or empty.


1 Answers

Take a look at Java 8 Optional class. It does exactly that: it avoids the ugly checks on null.

In your case, you could use this snippet of code to avoid them:

Car car = dao.getCar();
Optional<Car> optionalCar = Optional.ofNullable(car); 
Optional<Power> optionalPower = getPowerIfPresent(optionalCar);

Power power = Optional.empty();
if(optionalPower.isPresent()) {
    power = optionalPower.get();
}

after writing a function that returns the power of a given car:

public static Optional<Power> getPowerIfPresent(Optional<Car> car) {
    return car
        .flatMap(c -> c.getEngine())
        .map(e -> e.getPower());
}
like image 198
aUserHimself Avatar answered Oct 14 '22 03:10

aUserHimself