notEqual()
is a ObjectUtils
class that is used to compare two objects for inequality, where either one or both objects may be null
.
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;
public static boolean notEqual(final Object object1, final Object object2)
final Object object1
: The first object.final Object object2
: The second object.The notEqual()
method returns true
if the objects are not equal; otherwise, it returns false
.
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 1String object1 = "hello";String object2 = "hello";System.out.printf("ObjectUtils.notEqual(%s, %s) = %s", object1, object2, ObjectUtils.notEqual(object1, object2));System.out.println();// Example 2object1 = "";object2 = "hello";System.out.printf("ObjectUtils.notEqual(%s, %s) = %s", object1, object2, ObjectUtils.notEqual(object1, object2));System.out.println();// Example 3object1 = null;object2 = "hello";System.out.printf("ObjectUtils.notEqual(%s, %s) = %s", object1, object2, ObjectUtils.notEqual(object1, object2));System.out.println();// Example 4object1 = null;object2 = null;System.out.printf("ObjectUtils.notEqual(%s, %s) = %s", object1, object2, ObjectUtils.notEqual(object1, object2));System.out.println();}}
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
object1 = "hello"
object2 = "hello"
The method returns false
, as the objects are equal.
object1 = ""
object2 = "hello"
The method returns true
, as the objects are not equal.
object1 = null
object2 = "hello"
The method returns true
, as the objects are not equal.
object1 = null
object2 = null
The method returns false
, as the objects are equal.