Apache Commons Lang ObjectUtils

Apache Commons Lang – ObjectUtils

The ObjectUtils class from the Apache Commons Lang3 has many static utility methods operating on Object instances. Let us look at them in this post.

Methods checking for null in var-args

There are four methods which let us check for the presence of null values among the arguments (var-args).


The allNotNull method checks if all the values in the array (var-args) are not nulls. If there is at least one null value among the passed arguments (or if the array is null), it will return a false.

In the below example, in the first call, all three values are non-null and hence it returns true. In the next two calls, since the passed arguments have at least one null value, we get false as the result.

System.out.println(ObjectUtils.allNotNull("a", "b", "c")); //true
System.out.println(ObjectUtils.allNotNull("a", "b", null)); //false
System.out.println(ObjectUtils.allNotNull(null, "b", "c")); //false

An useful application of this method is to validate that all arguments of a method are non-null as shown below.

private static void foo(String s, Integer i, Float f) {
    if (!ObjectUtils.allNotNull(s, i, f)) {
        throw new IllegalArgumentException("All of the arguments must be non-null");


The ObjectUtils#allNull method checks if all values in the given array are null. If we pass an empty array or a null, it will return true as well.

System.out.println(ObjectUtils.allNull(null,  null)); //true
System.out.println(ObjectUtils.allNull("a", "b", "c")); //false
System.out.println(ObjectUtils.allNull(null, "b", "c")); //false

In this example, only the first call will return true as all the elements passed are null.


The anyNotNull checks if any value in the given array is not null. In other words, if there is at least one non-null value, it returns true.

In the below example, the first two calls have at least one non-null value. Hence, it returns true. In the last call, it returns false, as all the values are null.

System.out.println(ObjectUtils.anyNotNull("a", "b", "c")); //true
System.out.println(ObjectUtils.anyNotNull(null, "b", "c")); //true
System.out.println(ObjectUtils.anyNotNull(null,  null)); //false


ObjectUtils#anyNull checks if any value in the given array is null. If any of the values are null, it will return true.

Here, since there are no null values in the first call to anyNull, it returns false. The last two calls have at least one null value and hence we get true as the result.

System.out.println(ObjectUtils.anyNull("a", "b", "c")); //false
System.out.println(ObjectUtils.anyNull(null, "b", "c")); //true
System.out.println(ObjectUtils.anyNull(null,  null)); //true

ObjectUtils – defaultIfNull and getIfNull

The next two methods we will look at are used to check if an argument is non-null. If yes, then it will return that value. Otherwise, we provide a way to return a default value if the first argument is null.

In defaultIfNull, we pass the default value as the second argument.

In the example shown below, for the third call, since the first argument is null, it returns the default value.

System.out.println(ObjectUtils.defaultIfNull("a", "b")); //a
System.out.println(ObjectUtils.defaultIfNull("", "b")); //""
System.out.println(ObjectUtils.defaultIfNull(null, "b")); //b

We pass a Supplier<T> to the getIfNull method which supplies the default value. This is useful when computing the default value is costly and hence done lazily, i.e., only when needed.

The same example used for defaultIfNull is rewritten to use a Supplier.

System.out.println(ObjectUtils.getIfNull("a", () -> {
    System.out.println("Running supplier");
    return "b";
})); //a
System.out.println(ObjectUtils.getIfNull("", () -> {
    System.out.println("Running supplier");
    return "b";
})); //""
System.out.println(ObjectUtils.getIfNull(null, () -> {
    System.out.println("Running supplier");
    return "b";
})); //b

Note: It prints the string Running supplier only for the last call.

ObjectUtils – firstNonNull and getFirstNonNull

The firstNonNull method takes a var-args argument and returns the first value in the array which is not null. If all the values are null or if the array is null or empty, then it returns a null.

System.out.println(ObjectUtils.firstNonNull("a", null, "c")); //a
System.out.println(ObjectUtils.firstNonNull(null, null, "c")); //c

The getFirstNonNull method is similar, but takes a var-args of suppliers. It invokes the suppliers in order and returns the first return value which is non-null. Once a non-null value is obtained, all following suppliers are not executed anymore.

Supplier<String> supplier1 = () -> {
    System.out.println("Running supplier 1");
    return "a";
Supplier<String> supplier2 = () -> {
    System.out.println("Running supplier 2");
    return "b";
Supplier<String> supplier3 = () -> {
    System.out.println("Running supplier 3");
    return "c";
System.out.println(ObjectUtils.getFirstNonNull(supplier1, supplier2, supplier3));

In the above example, invoking the first supplier will result in a non-null value and it returns it. This prints,

Running supplier 1

In the below example, the first two suppliers return null and only the last supplier returns a non-null value.

Supplier<String> supplier1 = () -> {
    System.out.println("Running supplier 1");
    return null;
Supplier<String> supplier2 = () -> {
    System.out.println("Running supplier 2");
    return null;
Supplier<String> supplier3 = () -> {
    System.out.println("Running supplier 3");
    return "c";
System.out.println(ObjectUtils.getFirstNonNull(supplier1, supplier2, supplier3));


Running supplier 1
Running supplier 2
Running supplier 3


There are two overloaded compare methods. They are used to compare two Comparable values in a null-safe fashion.

The first simple overloaded ObjectUtils#compare method takes two Comparable instances (c1 and c2) and returns the result of comparing them, i.e., a negative value if c1 < c2, zero if c1 = c2 and a positive value if c1 > c2.

System.out.println(ObjectUtils.compare(1, 0)); //1
System.out.println(ObjectUtils.compare(1, 2)); //-1
System.out.println(ObjectUtils.compare(1, 1)); //0

By default, it considers a null value to be less than a non-null value. Examples involving null values follow.

System.out.println(ObjectUtils.compare(1, null)); //1
System.out.println(ObjectUtils.compare(null, 1)); //-1
System.out.println(ObjectUtils.compare(null, null)); //0

In the first check, since 1 > null, it returns 1. The inverse of this is the second call.

The second overloaded method takes an additional boolean flag called nullGreater. We can set it to true to consider a null to be greater than a non-null value. Setting it to false would be equivalent to using the first version of ObjectUtils#compare seen earlier.

We get inverted results when setting nullGreater as true for the same examples seen earlier.

System.out.println(ObjectUtils.compare(1, null, true)); //-1
System.out.println(ObjectUtils.compare(null, 1, true)); //1
System.out.println(ObjectUtils.compare(null, null, true)); //0

ObjectUtils – hashCodeHex, identityHashCodeHex

The hashCodeHex method finds the hash code of the passed object and returns the hexadecimal value of it. It is a shorthand for Integer.toHexString(Objects.hashCode(object)).

System.out.println(ObjectUtils.hashCodeHex("str")); //1be31

The identityHashCodeHex finds the identity hash code for the passed object and returns the hex value of it. It is a shorthand for Integer.toHexString(System.identityHashCode(object)).

System.out.println(ObjectUtils.identityHashCodeHex("str")); //7699a589


The identityToString returns the toString value that would be produced by the object if a class did not override toString itself.

System.out.println(ObjectUtils.identityToString("str")); //java.lang.String@7699a589

There are other overloaded identityToString methods which take one of these as the first argument (the second argument is an Object) – Appendable, StringBuffer or StringBuilder.

They all compute the toString what would be produced by the passed object if the class did not override toString itself and appends to the first argument (Appendable, StringBuffer or StringBuilder). An example using StringBuilder follows.

StringBuilder stringBuilder = new StringBuilder("str-1");
ObjectUtils.identityToString(stringBuilder, "str");
System.out.println(stringBuilder); //str-1java.lang.String@7699a589

ObjectUtils – isArray, isEmpty and isNotEmpty

The isArray method takes an Object as argument and checks if it is an array (an Object array or a primitive array) in a null-safe manner.

System.out.println(ObjectUtils.isArray(new int[]{})); //true
System.out.println(ObjectUtils.isArray(new int[]{1, 2})); //true
System.out.println(ObjectUtils.isArray("a")); //false

The is empty method checks if the passed object is empty or null. It supports the below types:

  • CharSequence: Checks if the length is zero
  • Array: An array is empty if its length is zero.
  • Collection: A collection is empty if it has no elements (size = 0)
  • Map: A map is empty if it has no mappings (size = 0)
  • Optional: An optional is empty if Optional.isPresent returns false.

Examples of all these types are shown below.

System.out.println(ObjectUtils.isEmpty(null)); //true
System.out.println(ObjectUtils.isEmpty("")); //true
System.out.println(ObjectUtils.isEmpty(new int[]{})); //true
System.out.println(ObjectUtils.isEmpty(List.of())); //true
System.out.println(ObjectUtils.isEmpty(Map.of())); //true
System.out.println(ObjectUtils.isEmpty(Optional.empty())); //true

System.out.println(ObjectUtils.isEmpty("str")); //false
System.out.println(ObjectUtils.isEmpty(new int[]{1})); //false
System.out.println(ObjectUtils.isEmpty(List.of(1))); //false
System.out.println(ObjectUtils.isEmpty(Map.of("a", 1))); //false
System.out.println(ObjectUtils.isEmpty(Optional.of("a"))); //false

The ObjectUtils.isNotEmpty does the reverse of isEmpty, i.e., checks if the object is not empty and not null.

System.out.println(ObjectUtils.isNotEmpty(null)); //false
System.out.println(ObjectUtils.isNotEmpty("")); //false
System.out.println(ObjectUtils.isNotEmpty(new int[]{})); //false
System.out.println(ObjectUtils.isNotEmpty(List.of())); //false
System.out.println(ObjectUtils.isNotEmpty(Map.of())); //false
System.out.println(ObjectUtils.isNotEmpty(Optional.empty())); //false

System.out.println(ObjectUtils.isNotEmpty("str")); //true
System.out.println(ObjectUtils.isNotEmpty(new int[]{1})); //true
System.out.println(ObjectUtils.isNotEmpty(List.of(1))); //true
System.out.println(ObjectUtils.isNotEmpty(Map.of("a", 1))); //true
System.out.println(ObjectUtils.isNotEmpty(Optional.of("a"))); //true

ObjectUtils – max, min, median and mode

The max and the min methods takes a var-args of Comparable values and returns the maximum and the minimum value among them, respectively. These are null-safe operations, i.e., there can be null values passed.

System.out.println(ObjectUtils.max(5, 3, 6, 4)); //6
System.out.println(ObjectUtils.max(5, 3, null, 6, null)); //6

System.out.println(ObjectUtils.min(5, 3, 6, 4)); //3
System.out.println(ObjectUtils.min(5, 3, null, 6, null)); //3

The median takes a var-args of Comparables and returns the median value (the middle value when the passed values are ordered as per their natural order).

System.out.println(ObjectUtils.median(1, 2, 3, 4, 5)); //3
System.out.println(ObjectUtils.median("a", "bbbb", "cc")); //bbbb

If the number of values passed is even, then it returns the lower of the two middle values.

System.out.println(ObjectUtils.median(1, 2, 4, 3, 5, 6)); //3

There is an overloaded median method where we can pass a custom Comparator to order the elements. In the below code, we order the strings by their length. Hence, the sorted ordering would be [a, cc, bbbb] and hence the median value is cc.

Comparator<String> compareByLength = Comparator.comparingInt(String::length);
System.out.println(ObjectUtils.median(compareByLength, "a", "bbbb", "cc")); //cc

The mode method returns the most frequently occurring value. In the below example, the value 4 is present three times (the most).

System.out.println(ObjectUtils.mode(1, 1, 4, 5, 4, 4, 7, 3)); //4


The requireNonEmpty takes an object and checks if it is empty or not (using ObjectUtils#isEmpty method seen earlier). If it is empty, it throws an IllegalArgumentException. This method is useful to validate the method and constructor arguments.

private static class MyClass {
    private final String s;

    public MyClass(String s) {
        this.s = ObjectUtils.requireNonEmpty(s);

When we pass an empty or null value for the constructor argument (new MyClass("") or new MyClass(null)), then it throws an IllegalArgumentException with message as “object”.

There is an overloaded method to which we can pass a custom message which it uses to throw the IllegalArgumentException.

private static class MyClass {
    private final String s;
    public MyClass(String s) {
        this.s = ObjectUtils.requireNonEmpty(s, "Parameter s cannot be empty");

When passed an empty or null string to this constructor, we get the below exception with the customized message.

java.lang.IllegalArgumentException: Parameter s cannot be empty


There are two overloaded toString methods. The first takes an object and a Supplier<String>. It returns the toString of the passed object. If it is null, then it returns the result of invoking the supplier.

Supplier<String> supplier = () -> {
    System.out.println("Returning toString from supplier");
    return "supplier-toString";
System.out.println(ObjectUtils.toString("str", supplier));
System.out.println(ObjectUtils.toString("", supplier));
System.out.println(ObjectUtils.toString(null, supplier));

In the first two calls, the passed object’s toString will be non-null and it returns them. In the last call, it will use the passed supplier to return the toString value.



Returning toString from supplier

In the overloaded method, rather than passing the object, we pass a Supplier<Object> along with Supplier<String> (as before). The result (output) will be the same as before.

System.out.println(ObjectUtils.toString(() -> "str", supplier));
System.out.println(ObjectUtils.toString(() -> "", supplier));
System.out.println(ObjectUtils.toString(() -> null, supplier));


In this post, we looked at the various useful utility methods from the Apache Commons Lang3 ObjectUtils class. You can learn more about other utilities from the apache-commons library here.

Leave a Reply