Skip to content

Best way to handle nulls in Java

The Best Feeling at starting stage of my development is seeing the Output without ‘NullpointerException‘, but its very difficult. So handling null values is more important in Coding to get a clear and satisfied Result. Let see how to handle nulls in Java

Optional Class

we have so many ways to compare NULL string, I.e Optional in Java 8 as below:

import java.util.Optional;
String str= null;
Optional<String> str2 = Optional.ofNullable(str);

then use isPresent() , it will return false if str2 contains NULL otherwise true

if(str2.isPresent())
{
//If No NULL 

else
{
//If NULL
}

The above example is little complicated, but Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as ‘available’ or ‘not available’ instead of checking null values.

Reference

Docs Oracle

Simplest Way

Simply you can check the String variable is null, use the following statement.

if(myString==null)//It's good
if (Optional.ofNullable(myString).isPresent()) // Complicated
if (Objects.nonNull(myString)) // better, but still Complicated
  1. null is a keyword in Java, "null" is just a string of text.

Deference Null

If a variable is null, you cannot deference it.

That means you can not invoke methods on it.

So… The following if statement will throw a NullPointerException every time the first clause is true:

if (myString == null && myString.length() == 0)

In other words: if myString is null, you CANNOT  invoke the length method on myString.

Happy Learning 🙂

See also  Check if BigDecimal variable is zero in Java (BigDecimal == 0)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.