Here's the code of ObjectUtils.equals(..):

public static boolean equals(Object object1, Object object2) {
     if (object1 == object2) {
       return true;
     }
     if ((object1 == null) || (object2 == null)) {
       return false;
    }
    return object1.equals(object2);
}

ObjecUtils docs state clearly that objects passed can be null.

Now on the matter whether true should be returned if you compare two nulls. In my opinion - no, because:

  • when you compare two objects, you are probably going to do something with them later on. This will lead to a NullPointerException
  • passing two nulls to compare means that they got from somewhere instead of "real" objects, perhaps due to some problem. In that case comparing them alone is wrong - the program flow should have halted before that.
  • In a custom library we're using here we have a method called equalOrBothNull() - which differs from the equals method in this utility in the null comparison.
Answer from Bozho on Stack Overflow
Top answer
1 of 3
13

Here's the code of ObjectUtils.equals(..):

public static boolean equals(Object object1, Object object2) {
     if (object1 == object2) {
       return true;
     }
     if ((object1 == null) || (object2 == null)) {
       return false;
    }
    return object1.equals(object2);
}

ObjecUtils docs state clearly that objects passed can be null.

Now on the matter whether true should be returned if you compare two nulls. In my opinion - no, because:

  • when you compare two objects, you are probably going to do something with them later on. This will lead to a NullPointerException
  • passing two nulls to compare means that they got from somewhere instead of "real" objects, perhaps due to some problem. In that case comparing them alone is wrong - the program flow should have halted before that.
  • In a custom library we're using here we have a method called equalOrBothNull() - which differs from the equals method in this utility in the null comparison.
2 of 3
5

Am I right to be concerned and to want to avoid using the ObjectUtils.equals() where ever possible?

No. What you need to consider equals depends on your requirements. And wanting to consider two nulls equal and any non-null unequal to a null without having to deal with NullPointerExceptions is a very, very common requirement (e.g. when you want to fire value-change events from a setter).

Actually, it's how equals() in general should work, and typically, half of that behvaiour is implemented (the API doc of Object.equals() states "For any non-null reference value x, x.equals(null) should return false.") - that it doesn't work the other way round is mainly due to technical restrictions (the language was designed without multiple dispatch to be simpler).

🌐
Educative
educative.io › answers › what-is-objectutilscompare-in-java
What is ObjectUtils.compare() in Java?
the methods in Java that can be called without creating an object of the class. method of the ObjectUtils class that is used to compare two comparables.
🌐
Apache Commons
commons.apache.org › proper › commons-lang › apidocs › org › apache › commons › lang3 › ObjectUtils.html
ObjectUtils (Apache Commons Lang 3.21.0-SNAPSHOT API)
Compares two objects for inequality, where either one or both objects may be null. ObjectUtils.notEqual(null, null) = false ObjectUtils.notEqual(null, "") = true ObjectUtils.notEqual("", null) = true ObjectUtils.notEqual("", "") = false ObjectUtils.notEqual(Boolean.TRUE, null) = true ...
🌐
Baeldung
baeldung.com › home › java › core java › comparing objects in java
Comparing Objects in Java | Baeldung
October 10, 2025 - It’s a generic method that takes two Comparable arguments of that generic type and returns an Integer. ... String first = new String("Hello!"); String second = new String("How are you?"); assertThat(ObjectUtils.compare(first, second)).isNegative();
🌐
Hotexamples
java.hotexamples.com › examples › org.apache.commons.lang3 › ObjectUtils › compare › java-objectutils-compare-method-examples.html
Java ObjectUtils.compare Examples, org.apache.commons.lang3.ObjectUtils.compare Java Examples - HotExamples
public int compareTo(final FileDetails o) { if (o == null) { throw new NullPointerException(); } // N.B. this is in reverse order to how we'd normally compare int result = o.getFile().compareTo(file); if (result == 0) { result = ObjectUtils.compare(o.getLastModified(), lastModified); } return result; } Example #2 ·
🌐
Tabnine
tabnine.com › home page › code › java › org.apache.commons.lang3.objectutils
org.apache.commons.lang3.ObjectUtils.compare java code examples | Tabnine
Returns the first value in the array which is not null. If all the values are null or the array is n ... Compares two objects for inequality, where either one or both objects may be null.
🌐
Program Creek
programcreek.com › java-api-examples
org.apache.commons.lang.ObjectUtils#compare
public int compare(ResolvedArtifact artifact1, ResolvedArtifact artifact2) { int diff = artifact1.getName().compareTo(artifact2.getName()); if (diff != 0) { return diff; } diff = ObjectUtils.compare(artifact1.getClassifier(), artifact2.getClassifier()); if (diff != 0) { return diff; } diff = artifact1.getExtension().compareTo(artifact2.getExtension()); if (diff != 0) { return diff; } diff = artifact1.getType().compareTo(artifact2.getType()); if (diff != 0) { return diff; } // Use an arbitrary ordering when the artifacts have the same public attributes return artifact1.hashCode() - artifact2.hashCode(); } Example 2 ·
🌐
Program Creek
programcreek.com › java-api-examples
org.apache.commons.lang3.ObjectUtils#compare
@Override public int compare(PicListItemModel firstModel, PicListItemModel secondModel) { String firstDisplayName; String secondDisplayName; if (!TextUtils.isEmpty(firstModel.getPersonId())) { firstDisplayName = firstModel.getPersonName(); } else { firstDisplayName = firstModel.getDeviceName(); } if (!TextUtils.isEmpty(secondModel.getPersonId())) { secondDisplayName = secondModel.getPersonName(); } else { secondDisplayName = secondModel.getDeviceName(); } return ObjectUtils.compare(firstDisplayName.toUpperCase(), secondDisplayName.toUpperCase()); }
🌐
Apache Commons
commons.apache.org › proper › commons-lang › javadocs › api-3.9 › org › apache › commons › lang3 › ObjectUtils.html
ObjectUtils (Apache Commons Lang 3.9 API)
Compares two objects for equality, where either one or both objects may be null. ObjectUtils.equals(null, null) = true ObjectUtils.equals(null, "") = false ObjectUtils.equals("", null) = false ObjectUtils.equals("", "") = true ObjectUtils.equals(Boolean.TRUE, null) = false ObjectUtils.equa...
Find elsewhere
🌐
Java2s
java2s.com › example › java-api › org › apache › commons › lang3 › objectutils › compare-2-3.html
Example usage for org.apache.commons.lang3 ObjectUtils compare
@Override public ProposalDevelopmentBudgetExt getFinalBudgetVersion(ProposalDevelopmentDocument parentDocument) { ProposalDevelopmentBudgetExt finalBudget = parentDocument.getDevelopmentProposal().getFinalBudget(); if (finalBudget == null) { return parentDocument.getDevelopmentProposal().getBudgets().stream().sorted((b1, b2) -> { return ObjectUtils.compare(b1.getBudgetVersionNumber(), b2.getBudgetVersionNumber()) * -1; }).findFirst().orElse(null);/*from w w w .j a v a2 s.c o m*/ } else { return finalBudget; } }
🌐
Apache Commons
commons.apache.org › proper › commons-lang › javadocs › api-3.1 › org › apache › commons › lang3 › ObjectUtils.html
ObjectUtils (Commons Lang 3.1 API) - Apache Commons
ObjectUtils.equals(null, null) ... Boolean.TRUE) = true ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false ... Compares two objects for inequality, where either one or both objects may be null....
🌐
GitHub
github.com › apache › commons-lang › blob › master › src › main › java › org › apache › commons › lang3 › ObjectUtils.java
commons-lang/src/main/java/org/apache/commons/lang3/ObjectUtils.java at master · apache/commons-lang
* Compares two objects for equality, where either one or both · * objects may be {@code null}. * * <pre> * ObjectUtils.equals(null, null) = true · * ObjectUtils.equals(null, "")  ...
Author   apache
🌐
Atlassian
docs.atlassian.com › software › jira › docs › api › 6.2.7 › com › atlassian › jira › util › ObjectUtils.html
ObjectUtils (Atlassian JIRA 6.2.7 API)
public class ObjectUtils · extends Object · public static boolean isNotEmpty(Object o) public static org.apache.commons.collections.Predicate getIsSetPredicate() public static boolean isValueSelected(Object selectValue) public static boolean equalsNullSafe(Object o1, Object o2) Compares the two objects.
🌐
Tabnine
tabnine.com › home page › code › java › org.apache.commons.lang.objectutils
org.apache.commons.lang.ObjectUtils.compare java code examples | Tabnine
/** * Compares two list items by comparing the label and value properties, respectively. * * @param o Item to compare. * @return Result of the comparison. */ @Override public int compareTo(Listitem o) { int cmp = ObjectUtils.compare(getLabel(), ...
🌐
Java2s
java2s.com › example › java-api › org › apache › commons › lang › objectutils › compare-2-1.html
Example usage for org.apache.commons.lang ObjectUtils compare
@Override public int compareTo(Site other) { if (this.equals(other)) return 0; int nameDiff = ObjectUtils.compare(this.name, other.name); if (nameDiff != 0) return nameDiff; return ObjectUtils.compare(this.id, other.id); }
🌐
Spring
docs.spring.io › spring-framework › docs › current › javadoc-api › org › springframework › util › ObjectUtils.html
ObjectUtils (Spring Framework 7.0.6 API)
Compares arrays with Arrays.equals, performing an equality check based on the array elements rather than the array reference.
🌐
Java Tips
javatips.net › api › org.apache.commons.lang3.objectutils.compare
Java Examples for org.apache.commons.lang3.ObjectUtils.compare
@Override public int compareTo(TestTag otherTag) { int typeComparison = compare(getType(), otherTag.getType()); if (typeComparison != 0) { return typeComparison; } else { return getName().compareToIgnoreCase(otherTag.getName()); } }
Top answer
1 of 3
4

Your Question is very vague, I don't really know what you are talking about, so I'll go in several Directions.

"compare my Objects" can mean several things. In Java, this usually means comparing them for sorting, i.e. through the Comparable / Comparator interfaces. While ObjectUtils does provide a null-safe compare method, it won't help you beyond that. What you need is either a custom Comparator or for your objects to implement Comparable. CompareToBuilder can help you with both, to a certain extent:

public class SomeBean implements Comparable<SomeBean>{

    private String foo;
    private int bar;
    private List<String> baz;

    public int compareTo(SomeBean other) {
        return new CompareToBuilder()
        .append(foo, other.foo)
        .append(bar, other.bar)
        .append(baz, other.baz)
        .toComparison();
    }

}

If, on the other hand, you want to compare the properties of different object types, then you are looking in the totally wrong direction. Have a look at Commons / BeanUtils instead. Sample code:

public class BeanUtilsTester {

    public static class Foo{
        private String foo="foo";
        public String getFoo() {return foo;}
        public void setFoo(String foo) {this.foo = foo;}
        private Integer bar=123;
        public Integer getBar() {return bar;}
        public void setBar(Integer bar) {this.bar = bar;}
        private List<String> squoggle=Arrays.asList("abc","def");
        public List<String> getSquoggle() {return squoggle;}
        public void setSquoggle(List<String> squoggle) {this.squoggle = squoggle;}
    }

    public static class Bar{
        private String foo="bar";
        public String getFoo() {return foo;}
        public void setFoo(String foo) {this.foo = foo;}
        private Integer bar=456;
        public Integer getBar() {return bar;}
        public void setBar(Integer bar) {this.bar = bar;}
        private String[] fiddle=new String[]{"abc","def"};
        public String[] getFiddle() {return fiddle;}
        public void setFiddle(String[] fiddle) {this.fiddle = fiddle;}
    }

    public static void main(String[] args) throws Exception{
        Foo foo = new Foo();
        Bar bar = new Bar();
        Map<String,Object> fooProps = BeanUtils.describe(foo);
        Map<String,Object> barProps = BeanUtils.describe(bar);
        fooProps.keySet().retainAll(barProps.keySet());
        BeanUtils.populate(bar, fooProps);
        assertEquals(foo.getFoo(),bar.getFoo());
        assertEquals(foo.getBar(), bar.getBar());
    }

}

And if you just want to implement equals() correctly, look at EqualsBuilder:

@Override
public boolean equals(Object obj) {
    if (obj instanceof SomeBean) {
        SomeBean other = (SomeBean) obj;
        return new EqualsBuilder()
                .append(foo, other.foo)
                .append(bar, other.bar)
                .append(baz, other.baz)
                .isEquals();
    }
    return false;
}
2 of 3
0

ObjectUtils will work just fine with comparing user defined objects. Of course you'll need to implement the Comparable interface in any object that you'd like to compare using the library functions.

🌐
Apache Commons
commons.apache.org › proper › commons-lang › javadocs › api-release › org › apache › commons › lang3 › ObjectUtils.html
ObjectUtils (Apache Commons Lang 3.11 API)
Compares two objects for inequality, where either one or both objects may be null. ObjectUtils.notEqual(null, null) = false ObjectUtils.notEqual(null, "") = true ObjectUtils.notEqual("", null) = true ObjectUtils.notEqual("", "") = false ObjectUtils.notEqual(Boolean.TRUE, null) = true ...