Java как проверить на null
Перейти к содержимому

Java как проверить на null

  • автор:

Working with Nulls in Java

In this article, we will learn some ways to deal with Null value in Java. Let’s get started.

Table of contents

Working with Reference types and Nulls

Null and Reference types

In the conference, in 2009, Sir Charles Antony Richard Hoare apologized for introducing null references in the programming language Algol Wz in 1965.

Null is useful concept, it allows modeling optional data. For example, for certain the type of books, ISBN numbers are optional.

Null also allow us to model data that hasn’t been entered yet, but it will be available at some point. For example, a book record can be created before the book’s finished and the exact number of pages is known.

Null can be used for either the initialization, too. For example, if a class manages its own memory, when an element is free, it should be noted out to avoid memory leaks.

From a technical point of view, null is a value that indicates that our reference does not refer to an object.

In assignment statement, it has three parts. The first part declares a reference variable. The second part creates an object of the type book telling the JVM to allocates space for a new book object in memory. Finally, the third part assigns the book object to a reference variable.

We also cannot meet the object creation, and in this case, the reference Book would refer to nothing at all because for all reference types, null is the default value. In other words, these two statements are equivalent.

–> Nulls can be completely avoided in Java.

Traditional ways to dealing with Nulls

The most common ways of checking for Nulls.

First, we use assertions.

If we use assertion, Error will be thrown.

In this way, there’s no extra benefits, but some people prefer it.

These methods are concise, readble, standard and prevent any kind of typos. However, something to consider is that the Objects.requireNonNull() method throws a NullPointerException is the object is null . So everything seems to lead us to exception, if we do nothing and try to call a method on a Null reference, Java will throw NullPointerException .

Use try/catch version will have better performance because there’s no checking for null. Exceptions may be a big cheaper in terms of performance. But using exception in this way, it’s about practice because it leads to go, hard to understand.

Best practices for data that we don’t control

We can clarify the data that flows through an application in two types.

Below is an image that describes that our flow’s data in application.

The data that we do not control is the data that is sent from Client to Server. It means that data from Presentation layer to Service layer.

For parts of the application where we don’t have control of the data:

Document our public API

It means that every class, interface, constructor, methods should have Java doc comments.

For methods describe the contract:

  • preconditions
  • postconditions
  • parameters
  • return values

Always validate parameters

    At the beginning of the method, use the general principle fail-fast.

If an invalid parameter value is passed to the method and the method checks for this before continuing its execution, it can take appropriate action.

There are two options for this case:

Replace the null value with some default value such as using empty string, a negative value or an empty List.

This solution is not always the right choice. It can cause the other errors.

Throw exceptions to indicate that an invalid value has been received.

We can choose one of the NullPointerException or IllegalArgumentException and use it consistently.

Best practice for data that we control

There is no need to check for null in every method when:

never pass null as an argument.

In this case, we can do two things:

    Use primitives instead of wrapper classes.

For optional parameters, we can overload the method with different sets of parameters.

In an above code, if the publicationDate variable is optional, instead of doing like the above code, it’s better to have the overloaded methods like the below.

never return null.

If null means that something could not be found, instead of using null value, we can return an empty collections.

These methods will not have to handle the null value.

So, the solutions for never return null are:

  • Return empty collection
  • Use Null Object pattern
  • Use Optional type

Checking for Null using annotations

Belows are some annotations in org.springframework.lang package.

In order to configure this annotation, we have to define it in the package-info.java file of the root directory package.

Bean Validation Annotations

Bean validation is the standard validation of specification, is defined by JSR 303 for its first version and JSR 380 for its second version.

Some annotations that we need to know:

  • @NotNull
  • @Size
  • @Min/@Max
  • @PositiveOrZero

Hibernate validator is the reference implementation of the specification, hibernate is associated with the persistent layer and that can be a source of confusion, especially about two things:

Does Hibernate Validator only validate objects of the domain model?

No, it validates objects in all layers.

Are @NotNull and @Column(nullable = false) equivalent?

No, the @Column annotation is part of the JPA specification. However, it doesn’t perform any validation if we annotate fields. If Hibernate creates the table, it adds a not null constraint to the database column, the database is the one that checks if the value is not null when we insert or update a record.

@NotNull is a part of the Bean Validation specification. It triggers a validation during an update or persist lifecycle event. It validates at the applicaltion level. If it fail, Hibernate will not execute any SQL statement.

Project Lombok Annotations

Project Lombok is a library that generates boilerplate methods such as getter/setter. Lombok works as an annotation post-processor. It reads the annotations during the complication process,

Some annotations of this library:

  • @NonNull annnotation for parameters of methods and constructors. It also used with the @Data annnotation

To choose an annotation library, consider:

  • At what point the null check is performed.
  • Where we can use the annotations.
  • Tool and language interoperability and compability.

Using the Null Object pattern

In order to use Null Object pattern, we can refer the article Null Object pattern.

So, instead of using a null reference to represent the absence of an object, it uses an object that implements the expected interface but does nothing, hiding the details from its collaborators.

Some notes about Null Object pattern:

  • It’s not a kind of GoF patterns.
  • It was described in a article The Null Object pattern by Bobby Woolf. And later, it was published in the Pattern Languages of Program Design Vol.3.
  • The other names of this pattern are Active nothing, Stub.
  • The other pattern that has the same idea with this Null Object pattern is the Special pattern.

Using Optional instead of Null

Belows are some article we need to read:

Wrapping up

Null is a value that indicates that a reference does not refer to an object.

The type of the literal value null is Null. That’s why use null with instanceof() will return false.

If we use null object, Java will throw a NullPointerException. To avoid a NullPointerException, developers traditionally use:

Check if an Object Is Null in Java

Check if an Object Is Null in Java

This tutorial will go through the methods to check if an object is null in Java with some briefly explained examples.

Java Check if Object Is Null Using the == Operator

As an example, we have created two classes — User1 and User2 . The class User1 has one instance variable name and the Getter and Setter methods to update and retrieve the instance variable name . The User2 class has one method, getUser1Object , which returns the instance of class User1 .

In the main method, we create an object of the User2 class named user and call the getUser1Object() on it, which returns the instance of the class User1 . Now we check if the instance of the User1 class returned by the method is null or not by using the == operator in the if-else condition.

If the object returned is not null , we can set the name in the User1 class by calling the setter method of the class and passing a custom string as a parameter to it.

Java Check if Object Is Null Using java.utils.Objects

The java.utils.Objects class has static utility methods for operating an object. One of the methods is isNull() , which returns a boolean value if the provided reference is null, otherwise it returns false.

We have created two classes — User1 and User2 as shown in the code below. In the main method, we created an object of the User2 class using the new keyword and called the getUser1Object() method. It returns an object of class User1 , which we later store in getUser1Object .

To check if it is null, we call the isNull() method and pass the object getUserObject as a parameter. It returns true as the passed object is null.

Java: How to check if object is null?

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:

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

Niko Gamulin's user avatar

8 Answers 8

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.

Edited Java 8 Solution:

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.

I use this approach:

This way I find improves the readability of the line — as I read quickly through a source file I can see it’s a null check.

With regards to why you can’t call .equals() on an object which may be null ; if the object reference you have (namely ‘drawable’) is in fact null , it doesn’t point to an object on the heap. This means there’s no object on the heap on which the call to equals() can succeed.

Jared Burrows's user avatar

if (yourObject instanceof yourClassName) will evaluate to false if yourObject is null .

Jared Burrows's user avatar

The above line calls the «equals(. )» method on the drawable object.

So, when drawable is not null and it is a real object, then all goes well as calling the «equals(null)» method will return «false»

But when «drawable» is null, then it means calling the «equals(. )» method on null object, means calling a method on an object that doesn’t exist so it throws «NullPointerException»

To check whether an object exists and it is not null, use the following

In above condition, we are checking that the reference variable «drawable» is null or contains some value (reference to its object) so it won’t throw exception in case drawable is null as checking

Check if Object Is Null in Java

Check if Object is null Java

An object in Java is an instance of a class. It is a real entity existing in the memory opposite to the class that acts as a blueprint for the object.

The object represents data and methods for a particular entity that are defined by the class.

In this article, you will learn to check if the object contains a null reference in Java.

Comparison Operator to Check if Object Is Null in Java

The comparison operator (==) in Java is widely used to perform the comparison between two entities. The result of the comparison is boolean true if both the entities are the same, otherwise, the result is boolean false.

You can use this operator to check if an object is null in Java by comparing the object with the ‘null’ value.

The code defines a class named MyClass that has a String field name . There are two constructors to instantiate the object of the class.

The code defines two objects of the MyClass class named as myObj and myObj2 . The myObj object is not instantiated therefore it should have the null reference. The other object is instantiated making it a non-null object.

Check if an Object Is Null in Java

Check if an Object Is Null in Java

This tutorial will go through the methods to check if an object is null in Java with some briefly explained examples.

Java Check if Object Is Null Using the == Operator

Please enable JavaScript

As an example, we have created two classes — User1 and User2 . The class User1 has one instance variable name and the Getter and Setter methods to update and retrieve the instance variable name . The User2 class has one method, getUser1Object , which returns the instance of class User1 .

In the main method, we create an object of the User2 class named user and call the getUser1Object() on it, which returns the instance of the class User1 . Now we check if the instance of the User1 class returned by the method is null or not by using the == operator in the if-else condition.

If the object returned is not null , we can set the name in the User1 class by calling the setter method of the class and passing a custom string as a parameter to it.

Java Check if Object Is Null Using java.utils.Objects

The java.utils.Objects class has static utility methods for operating an object. One of the methods is isNull() , which returns a boolean value if the provided reference is null, otherwise it returns false.

We have created two classes — User1 and User2 as shown in the code below. In the main method, we created an object of the User2 class using the new keyword and called the getUser1Object() method. It returns an object of class User1 , which we later store in getUser1Object .

To check if it is null, we call the isNull() method and pass the object getUserObject as a parameter. It returns true as the passed object is null.

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

Java: How to check if object is null?

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:

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

Niko Gamulin's user avatar

8 Answers 8

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.

Edited Java 8 Solution:

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.

I use this approach:

This way I find improves the readability of the line — as I read quickly through a source file I can see it’s a null check.

With regards to why you can’t call .equals() on an object which may be null ; if the object reference you have (namely ‘drawable’) is in fact null , it doesn’t point to an object on the heap. This means there’s no object on the heap on which the call to equals() can succeed.

Jared Burrows's user avatar

if (yourObject instanceof yourClassName) will evaluate to false if yourObject is null .

Jared Burrows's user avatar

The above line calls the «equals(. )» method on the drawable object.

So, when drawable is not null and it is a real object, then all goes well as calling the «equals(null)» method will return «false»

But when «drawable» is null, then it means calling the «equals(. )» method on null object, means calling a method on an object that doesn’t exist so it throws «NullPointerException»

To check whether an object exists and it is not null, use the following

In above condition, we are checking that the reference variable «drawable» is null or contains some value (reference to its object) so it won’t throw exception in case drawable is null as checking

How to check a string against null in java?

string == null compares if the object is null. string.equals(«foo») compares the value inside of that object. string == «foo» doesn’t always work, because you’re trying to see if the objects are the same, not the values they represent.

If you try this, it won’t work, as you’ve found:

The reason is that foo is null, so it doesn’t know what .equals is; there’s no object there for .equals to be called from.

What you probably wanted was:

The typical way to guard yourself against a null when dealing with Strings is:

That way, if foo was null, it doesn’t evaluate the second half of the conditional, and things are all right.

The easy way, if you’re using a String literal (instead of a variable), is:

If you want to work around that, Apache Commons has a class — StringUtils — that provides null-safe String operations.

Another response was joking, and said you should do this:

Please don’t do that. You should only throw exceptions for errors that are exceptional; if you’re expecting a null, you should check for it ahead of time, and not let it throw the exception.

In my head, there are two reasons for this. First, exceptions are slow; checking against null is fast, but when the JVM throws an exception, it takes a lot of time. Second, the code is much easier to read and maintain if you just check for the null pointer ahead of time.

Check if Object Is Null in Java

Check if Object is null Java

An object in Java is an instance of a class. It is a real entity existing in the memory opposite to the class that acts as a blueprint for the object.

The object represents data and methods for a particular entity that are defined by the class.

In this article, you will learn to check if the object contains a null reference in Java.

Comparison Operator to Check if Object Is Null in Java

The comparison operator (==) in Java is widely used to perform the comparison between two entities. The result of the comparison is boolean true if both the entities are the same, otherwise, the result is boolean false.

You can use this operator to check if an object is null in Java by comparing the object with the ‘null’ value.

The code defines a class named MyClass that has a String field name . There are two constructors to instantiate the object of the class.

The code defines two objects of the MyClass class named as myObj and myObj2 . The myObj object is not instantiated therefore it should have the null reference. The other object is instantiated making it a non-null object.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *