Compare two objects in Java with possible null values

how to compare string with null value in java
java string equals null
java string compare
java string comparator
java null safe equals
string compare null c#
java spring compare
how to compare one string with multiple strings in java

I want to compare two strings for equality in Java, when either or both could be null, so I cannot simply call .equals(). What is the best way?

boolean compare(String str1, String str2) {


return ((str1 == str2) || (str1 != null && str1.equals(str2)));

This is what Java internal code uses (on other compare methods):

public static boolean compare(String str1, String str2) {
    return (str1 == null ? str2 == null : str1.equals(str2));

Compare two objects in Java with possible null values, Strings in Java represents an array of characters. They are represented by the String class.Using compareTo() methodThe compareTo()  Compare two objects in Java with possible null Compare two objects in Java with possible null values. 0 votes . 1 view. asked Nov 12, 2019 in Java by Anvi (10.2k

Since Java 7 you can use the static method java.util.Objects.equals(Object, Object) to perform equals checks on two objects without caring about them being null.

If both objects are null it will return true, if one is null and another isn't it will return false. Otherwise it will return the result of calling equals on the first object with the second as argument.

Comparing Strings with (possible) null values in java?, Also, if any of the two strings is null, then the method returns false. 2.3. Using equalsIgnoreCase(). Strings in Java represents an array of characters. They are represented by the String class. Using compareTo() method. The compareTo() method of the String class two Strings (char by char) it also accepts null values. This method returns an integer representing the result, if the value of the obtained integer is −

For these cases it would be better to use Apache Commons StringUtils#equals, it already handles null strings. Code sample:

public boolean compare(String s1, String s2) {
    return StringUtils.equals(s1, s2);

If you dont want to add the library, just copy the source code of the StringUtils#equals method and apply it when you need it.

Comparing Strings in Java, You could write the code like this, it is doing the same, but I think it is more readable, you almost don't need any comment, to assume the return value. Answers: Since Java 7 you can use the static method Objects.equals(Object, Object) to perform equals checks on two objects without caring about them being null. If both objects are null it will return true, if one is null and another isn’t it will return false.

For those on android, who can't use API 19's Objects.equals(str1, str2), there is this:

android.text.TextUtils.equals(str1, str2);

It is null safe. It rarely has to use the more expensive string.equals() method because identical strings on android almost always compare true with the "==" operand thanks to Android's String Pooling, and length checks are a fast way to filter out most mismatches.

Source Code:

 * Returns true if a and b are equal, including if they are both null.
 * <p><i>Note: In platform versions 1.1 and earlier, this method only worked  well if
 * both the arguments were instances of String.</i></p>
 * @param a first CharSequence to check
 * @param b second CharSequence to check
 * @return true if a and b are equal
public static boolean equals(CharSequence a, CharSequence b) {
    if (a == b) return true;
    int length;
    if (a != null && b != null && (length = a.length()) == b.length()) {
        if (a instanceof String && b instanceof String) {
            return a.equals(b);
        } else {
            for (int i = 0; i < length; i++) {
                if (a.charAt(i) != b.charAt(i)) return false;
            return true;
    return false;

Comparing two Strings which could be null or blank in a Comparator , Compares references, not values. The use of == with object references is generally limited to the following: Comparing to see if a reference is null. Comparing two  To compare two objects with the equals method, follow these four steps. Open your text editor and create a new file that will contain the circle class and a main method to test two circles for equality. Type in the following Java statements. According to the equals method, two circles are equal if they have the same radius.

Since version 3.5 Apache Commons StringUtils has the following methods:

static int  compare(String str1, String str2)
static int  compare(String str1, String str2, boolean nullIsLess)
static int  compareIgnoreCase(String str1, String str2)
static int  compareIgnoreCase(String str1, String str2, boolean nullIsLess)

These provide null safe String comparison.

Java: Comparing objects, If you compare a non-null String value to a null string then also it returns false. a couple of examples of comparing strings using compareTo() method in Java: Java Bean Components Java In some cases it is not possible to compare all the fields of an object in equal() method of an object, for example in the cases of identity objects, like the ones created with JPA @Entity. In those kind of cases if we want to check whether all fields

5 ways to Compare String Objects in Java, Checks if any value in the given array is not null . static <T> T Clone an object if possible. static <T int, compare(T c1, T c2, boolean nullGreater) Objects.​equals(Object, Object) in Java 7 and will be removed from future releases. Compares two objects for inequality, where either one or both objects may be null . If the two objects have the same values, equals() will return true. In the second comparison, equals()checks to see whether the passed object is null, or if it’s typed as a different class. If it’s a different class then the objects are not equal. Finally, equals() compares the objects’ fields. If two objects have the same field values, then the objects are the same.

ObjectUtils (Apache Commons Lang 3.10 API), We often need to compare the data of two variables or objects or the operator in Kotlin only compares the data or variables, whereas in Java or other There's no point in optimizing code when comparing to null explicitly. a == null will be  the return type of object.equals is already boolean. there's no need to wrap it in a method with branches. so if you want to compare 2 objects simply compare them: boolean b = objectA.equals(objectB); b is already either true or false.

Equality in Kotlin ('==', '===' and 'equals'), In Java, we can distinguish two kinds of equality. Object reference equality: when two object references point to the same object. Object value equality: when two  The two operators that can be used with object references are comparing for equality (==) and inequality (!=). These operators compare two values to see if they refer to the same object. Although this comparison is very fast, it is often not what you want.

  • possible duplicate of A better way to compare Strings which could be null
  • Why not just change the String types to Objects - making it more generic? And then it is the same as what you will get if you move to Java 7.
  • Which java class contains method you provided?
  • Hey! you shouldn't have a compare method returning true/false. Equals is not the same as compare. Compare should be useful for sorting. You should return <0, ==0 or >0 to indicate which one is lower/grater than the other
  • i suggest using Objects.equals(Object, Object) as Mark Rotteveel has pointed out in his answer (please upvote it)
  • @Eric that doesn't really make it less of a good answer. I am sure you wouldn't argue the best answer is always the one containing only code which is compatible with every java version that has always existed
  • this approach defers the type check until the runtime of the program. two consequences: it will be slower at runtime and IDE won't let you know if you by accident try to compare different types.
  • @averasko When you use Object.equals(Object) there is no compile time type check. The Objects.equals(Object, Object) works very much the same as a normal equals, and re inference/checks by IDE, those rules are heuristics that are also supported for Objects.equals(Object, Object) (eg IntelliJ IDEA 2016.2 has the same check for both the normal equals and the one from Objects).
  • I like this approach. No need to include some ApacheCommons library for things these days.
  • @SimonBaars This isn't running a function on a null object, this is a static method that you pass two arguments, which can be null, or a reference to an object.
  • imho this should be the accepted answer. I don't want to reinvent the wheel in every single application I write
  • This case returns false if both Strings are null which might not be the desired result.