Java – Check if object is null using Objects class static utility methods
Checking if object is null is a common problem in Java. To check that you can check if object itself is null or you can also use static utility methods of java.util.Objects class for operating on objects.
For instance, consider the following MyClass for our excercise
package com.sneppets.solution; public class MyClass { private int x; private int y; MyClass(){ } MyClass (int x, int y){ this.setX(x); this.setY(y); } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } }
In the following code you are checking object itself to check if the specified object reference is null
public static boolean checkObjectIfNull(MyClass obj) { if(obj == null) { return true; } return false; }
You can also use java.util.Objects class static utility methods like Objects.isNull(), Objects.nonNull() and Objects.requireNonNull() as shown below.
public static boolean checkObjectIfNull(MyClass obj) { if(Objects.isNull(obj)) { return true; } return false; }
Using Objects.requireNonNull(T obj)
public void checkObjectIfNull(MyClass obj) { Objects.requireNonNull(obj); //other code }
Using Objects.requireNonNull(T obj, String message) and throw customized NullPointerException.
public void checkObjectIfNull(MyClass obj) { Objects.requireNonNull(obj, "obj must not be null"); //other code }
Check if object not null
For instance let’s create an MyClass object and initialize x,y with some values and see how to check if object is not null
MyClass obj = new MyClass(2,3); if(obj2 != null) { System.out.println("Object is not null"); System.out.println(obj2.getX()); }
Further Learning
- How to get enum name using enum value in the lookup method
- Convert from ZonedDateTime to LocalDateTime with a timezone
- Java 8 – Convert LocalDate to Instant
- Check if key exists in jsonobject before fetching value for that key ?