[java] Check object empty

Basically how do you check if an object is null or empty. What I mean is that if I have an object instantiated but all its values or fields are null, the how do I check in code if it is empty?

I have tried;

if (doc != null){
.... do something

But it doesn't seem to work.

This question is related to java

The answer is


If your Object contains Objects then check if they are null, if it have primitives check for their default values.

for Instance:

Person Object 
name Property with getter and setter

to check if name is not initialized. 

Person p = new Person();
if(p.getName()!=null)

I have a way, you guys tell me how good it is.

Create a new object of the class and compare it with your object (which you want to check for emptiness).

To be correctly able to do it :

Override the hashCode() and equals() methods of your model class and also of the classes, objects of whose are members of your class, for example :

Person class (primary model class) :

public class Person {

    private int age;
    private String firstName;
    private String lastName;
    private Address address;

    //getters and setters

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((address == null) ? 0 : address.hashCode());
        result = prime * result + age;
        result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
        result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (address == null) {
            if (other.address != null)
                return false;
        } else if (!address.equals(other.address))
            return false;
        if (age != other.age)
            return false;
        if (firstName == null) {
            if (other.firstName != null)
                return false;
        } else if (!firstName.equals(other.firstName))
            return false;
        if (lastName == null) {
            if (other.lastName != null)
                return false;
        } else if (!lastName.equals(other.lastName))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Person [age=" + age + ", firstName=" + firstName + ", lastName=" + lastName + ", address=" + address
                + "]";
    }

}

Address class (used inside Person class) :

public class Address {

    private String line1;
    private String line2;

    //getters and setters

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((line1 == null) ? 0 : line1.hashCode());
        result = prime * result + ((line2 == null) ? 0 : line2.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Address other = (Address) obj;
        if (line1 == null) {
            if (other.line1 != null)
                return false;
        } else if (!line1.equals(other.line1))
            return false;
        if (line2 == null) {
            if (other.line2 != null)
                return false;
        } else if (!line2.equals(other.line2))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Address [line1=" + line1 + ", line2=" + line2 + "]";
    }

}

Now in the main class :

    Person person1 = new Person();
    person1.setAge(20);

    Person person2 = new Person();

    Person person3 = new Person();

if(person1.equals(person2)) --> this will be false

if(person2.equals(person3)) --> this will be true

I hope this is the best way instead of putting if conditions on each and every member variables.

Let me know !


In Java, you can verify using Object utils.

import static java.util.Objects.isNull;
if(IsNull(yourObject)){
  //your block here
}

This can be done with java reflection,This method returns false if any one attribute value is present for the object ,hope it helps some one

public boolean isEmpty()  {

    for (Field field : this.getClass().getDeclaredFields()) {
        try {
            field.setAccessible(true);
            if (field.get(this)!=null) {
                return false;
            }
        } catch (Exception e) {
          System.out.println("Exception occured in processing");
        }
    }
    return true;
}

You should check it against null.

If you want to check if object x is null or not, you can do:

    if(x != null)

But if it is not null, it can have properties which are null or empty. You will check those explicitly:

    if(x.getProperty() != null)

For "empty" check, it depends on what type is involved. For a Java String, you usually do:

    if(str != null && !str.isEmpty())

As you haven't mentioned about any specific problem with this, difficult to tell.


I suggest you add separate overloaded method and add them to your projects Utility/Utilities class.

To check for Collection be empty or null

public static boolean isEmpty(Collection obj) {
    return obj == null || obj.isEmpty();
}

or use Apache Commons CollectionUtils.isEmpty()

To check if Map is empty or null

public static boolean isEmpty(Map<?, ?> value) {
    return value == null || value.isEmpty();
}

or use Apache Commons MapUtils.isEmpty()

To check for String empty or null

public static boolean isEmpty(String string) {
    return string == null || string.trim().isEmpty();
}

or use Apache Commons StringUtils.isBlank()

To check an object is null is easy but to verify if it's empty is tricky as object can have many private or inherited variables and nested objects which should all be empty. For that All need to be verified or some isEmpty() method be in all objects which would verify the objects emptiness.


let suppose ,

data = {};

if( if(!$.isEmptyObject(data)))
{
     document.write("Object is empty);
}

else{
    document.write("Object is not empty);
}

It worked for me and its an easy way to check if object is empty or not