Javatpoint Logo
Javatpoint Logo

How to Check null in Java?

In Java, null is a literal. It is mainly used to assign a null value to a variable. A null value is possible for a string, object, or date and time, etc. We cannot assign a null value to the primitive data types such as int, float, etc.

In programming, usually we need to check whether an object or a string is null or not to perform some task on it. In order to check a null string, we have some predefined methods of string. Let's take some examples of different data types to understand how we can check whether they are null or not.

String

In Java, String can be null, empty, or blank, and each one of them is distinct.

1. An empty string is a string object having some value, but its length is equal to zero. For example:

2. A blank string is a string that has whitespace as its value. Its length is always greater than 0 and neither empty nor null. For example:

3. A null string has no value and makes a string null by assigning a null keyword as a value to it. For example:

In order to check whether a String is null or not, we use the comparison operator(==). Let's take an example of it to understand how we can use it for null checking.

NullCheckExample1.java

Output:

How to Check null in Java

Date andDateTime object

Date and DateTime both are the non-primitive data types, so they can store a null value. Let's take an example of a date and time object to understand how we can check a null date or datetime object.

NullCheckExample2.java

Output:

How to Check null in Java

Java Object

In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator. Let's take an example to understand how we can use the isNull() method or comparison operator for null check of Java object.

NullCheckExample3.java

Output:

How to Check null in Java

NullCheckExample4.java

Output:

How to Check null in Java
Next TopicJava Arrays Fill





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA