What is ObjectUtils.notEqual() in Java?

notEqual() is a staticthe 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 objects for inequality, where either one or both objects may be null.

How to import ObjectUtils

The definition of ObjectUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:


<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

For other versions of the commons-lang package, refer to the Maven Repository.

You can import the ObjectUtils class as follows:


import org.apache.commons.lang3.ObjectUtils;

Syntax


public static boolean notEqual(final Object object1, final Object object2)

Parameters

  • final Object object1: The first object.
  • final Object object2: The second object.

Return value

The notEqual() method returns true if the objects are not equal; otherwise, it returns false.

Code

The code below shows how the notEqual() method works:

import org.apache.commons.lang3.ObjectUtils;
public class Main{
public static void main(String[] args) {
// Example 1
String object1 = "hello";
String object2 = "hello";
System.out.printf("ObjectUtils.notEqual(%s, %s) = %s", object1, object2, ObjectUtils.notEqual(object1, object2));
System.out.println();
// Example 2
object1 = "";
object2 = "hello";
System.out.printf("ObjectUtils.notEqual(%s, %s) = %s", object1, object2, ObjectUtils.notEqual(object1, object2));
System.out.println();
// Example 3
object1 = null;
object2 = "hello";
System.out.printf("ObjectUtils.notEqual(%s, %s) = %s", object1, object2, ObjectUtils.notEqual(object1, object2));
System.out.println();
// Example 4
object1 = null;
object2 = null;
System.out.printf("ObjectUtils.notEqual(%s, %s) = %s", object1, object2, ObjectUtils.notEqual(object1, object2));
System.out.println();
}
}

Output

The output of the code will be as follows:


ObjectUtils.notEqual(hello, hello) = false
ObjectUtils.notEqual(, hello) = true
ObjectUtils.notEqual(null, hello) = true
ObjectUtils.notEqual(null, null) = false

Explanation

Example 1

  • object1 = "hello"
  • object2 = "hello"

The method returns false, as the objects are equal.

Example 2

  • object1 = ""
  • object2 = "hello"

The method returns true, as the objects are not equal.

Example 3

  • object1 = null
  • object2 = "hello"

The method returns true, as the objects are not equal.

Example 4

  • object1 = null
  • object2 = null

The method returns false, as the objects are equal.

Free Resources