Java Null Check Why Use == Instead of .Equals()

Java null check why use == instead of .equals()

They're two completely different things. == compares the object reference, if any, contained by a variable. .equals() checks to see if two objects are equal according to their contract for what equality means. It's entirely possible for two distinct object instances to be "equal" according to their contract. And then there's the minor detail that since equals is a method, if you try to invoke it on a null reference, you'll get a NullPointerException.

For instance:

class Foo {
private int data;

Foo(int d) {
this.data = d;
}

@Override
public boolean equals(Object other) {
if (other == null || other.getClass() != this.getClass()) {
return false;
}
return ((Foo)other).data == this.data;
}

/* In a real class, you'd override `hashCode` here as well */
}

Foo f1 = new Foo(5);
Foo f2 = new Foo(5);
System.out.println(f1 == f2);
// outputs false, they're distinct object instances

System.out.println(f1.equals(f2));
// outputs true, they're "equal" according to their definition

Foo f3 = null;
System.out.println(f3 == null);
// outputs true, `f3` doesn't have any object reference assigned to it

System.out.println(f3.equals(null));
// Throws a NullPointerException, you can't dereference `f3`, it doesn't refer to anything

System.out.println(f1.equals(f3));
// Outputs false, since `f1` is a valid instance but `f3` is null,
// so one of the first checks inside the `Foo#equals` method will
// disallow the equality because it sees that `other` == null

Java string null check by != null or !str.equals(null)?

1st one is better (and the only option), because 2nd one will throw NPE, when your value is actually null. As simple as that.

Try this out:

String str = null;
str.equals(null); // will throw `NPE`.

So basically, the test which you wanted to perform itself triggers a NullPointerException in the 2nd case. So, it is no choice.

How to prevent null check before equals

Use commons-lang:

org.apache.commons.lang.ObjectUtils.equals(Object object1, Object object2)

Source code:

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

From Apache

http://commons.apache.org/lang/

That's about equivalent to what you do in C#

Java null.equals(object o)

I generally use a static utility function that I wrote called equalsWithNulls to solve this issue:

class MyUtils {
public static final boolean equalsWithNulls(Object a, Object b) {
if (a==b) return true;
if ((a==null)||(b==null)) return false;
return a.equals(b);
}
}

Usage:

if (MyUtils.equalsWithNulls(s1,s2)) {
// do stuff
}

Advantages of this approach:

  • Wraps up the complexity of the full equality test in a single function call. I think this is much better than embedding a bunch of complex boolean tests in your code each time you do this. It's much less likely to lead to errors as a result.
  • Makes your code more descriptive and hence easier to read.
  • By explicitly mentioning the nulls in the method name, you convey to the reader that they should remember that one or both of the arguments might be null.
  • Does the (a==b) test first (an optimisation which avoids the need to call a.equals(b) in the fairly common case that a and b are non-null but refer to exactly the same object)

Difference between equals and == to compare with null?

You can never call the .equals() method on an object reference that is null.
It is a method, just like the rest, so if the object reference is truly null it will just throw a NullPointerException.

If you want to check if a reference is not pointing to any object, i.e. it is a null reference you must use the ==.

The equals() method on the other hand is used if you want to compare the data contained in the object. If the class in question overrides the equals(), like for example String does, then it will compare the contents of the object, rather than just whether it is the same object reference.

If you see an object like a box. == is comparing whether it is the same box while equals() compares the contents of two boxes.

Why is it impossible to compare a String and null with equals?

You call a method on a null, so it is like null.equals(null), null has no methods so it throws the exception.

If you dont want to use ==, you can use Objects.equals(yourString, null)

Compare two objects in Java with possible null values

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));
}

Java null String equals result

You cannot use the dereference (dot, '.') operator to access instance variables or call methods on an instance if that instance is null. Doing so will yield a NullPointerException.

It is common practice to use something you know to be non-null for string comparison. For example, "something".equals(stringThatMayBeNull).



Related Topics



Leave a reply



Submit