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).

Answer from sjr on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com › comparing-strings-with-possible-null-values-in-java
Comparing Strings with (possible) null values in java?
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 retu
Top answer
1 of 16
187

string == null compares if the object is null. string.equals("foo") compares the value inside of that object. string == "foo" doesn't always work, because you're trying to see if the objects are the same, not the values they represent.


Longer answer:

If you try this, it won't work, as you've found:

CopyString foo = null;
if (foo.equals(null)) {
    // That fails every time. 
}

The reason is that foo is null, so it doesn't know what .equals is; there's no object there for .equals to be called from.

What you probably wanted was:

CopyString foo = null;
if (foo == null) {
    // That will work.
}

The typical way to guard yourself against a null when dealing with Strings is:

CopyString foo = null;
String bar = "Some string";
...
if (foo != null && foo.equals(bar)) {
    // Do something here.
}

That way, if foo was null, it doesn't evaluate the second half of the conditional, and things are all right.

The easy way, if you're using a String literal (instead of a variable), is:

CopyString foo = null;
...
if ("some String".equals(foo)) {
    // Do something here.
}

If you want to work around that, Apache Commons has a class - StringUtils - that provides null-safe String operations.

Copyif (StringUtils.equals(foo, bar)) {
    // Do something here.
}

Another response was joking, and said you should do this:

Copyboolean isNull = false;
try {
    stringname.equalsIgnoreCase(null);
} catch (NullPointerException npe) {
    isNull = true;
}

Please don't do that. You should only throw exceptions for errors that are exceptional; if you're expecting a null, you should check for it ahead of time, and not let it throw the exception.

In my head, there are two reasons for this. First, exceptions are slow; checking against null is fast, but when the JVM throws an exception, it takes a lot of time. Second, the code is much easier to read and maintain if you just check for the null pointer ahead of time.

2 of 16
33
Copys == null

won't work?

🌐
Coderanch
coderanch.com › t › 545457 › java › comparing-values-equalsIgnoreCase-equals-NULL
comparing two values with equalsIgnoreCase and equals with NULL as first value. (Java in General forum at Coderanch)
Beware: it is only available in Java7. Or you can use an if (x != null) ... test. ... Hello Davies, You should not call equals() method using the reference which points to "null". In the first case yo will get NullPointerException obviously. but the second approach is correct.
Find elsewhere
🌐
Delft Stack
delftstack.com › home › howto › java › how to check whether an array is null empty
How to Check Whether an Array Is Null/Empty in Java | Delft Stack
February 2, 2024 - This is the case when array contains null values. import java.util.Arrays; import java.util.Objects; public class SimpleTesting { String[] arr = new String[10]; public static void main(String[] args) { SimpleTesting obj = new SimpleTesting(); Boolean containNull = Arrays.stream(obj.arr).allMatch(Objects::nonNull); if (!containNull) { System.out.println("Array is null"); } } }
🌐
Medium
medium.com › @thilinajayawardana_85346 › java-string-nullpointerexception-safe-equals-check-404481934e9b
Java String NullPointerException safe equals check | by Thilina Jayawardana | Medium
June 30, 2020 - Java String NullPointerException safe equals check If you compare two Strings in Java, normally you would use the equals method to compare them to see if they are similar. This will be some common …
🌐
TutorialsPoint
tutorialspoint.com › how-to-check-if-an-array-is-empty-or-not-in-java
How to Check if an Array is Empty or Not in Java
public class Main{ public static void main(String[] args){ int arr[] = null; //check if array is equal to null or not by using equal to operator if(arr == null) { System.out.println("Empty array"); } else { System.out.println("Not an empty array"); } } } Empty array · In this article, we explored ...
Top answer
1 of 16
408

You may also understand the difference between null and an empty string this way:

Original image by R. Sato (@raysato)

2 of 16
251

"" is an actual string, albeit an empty one.

null, however, means that the String variable points to nothing.

a==b returns false because "" and null do not occupy the same space in memory--in other words, their variables don't point to the same objects.

a.equals(b) returns false because "" does not equal null, obviously.

The difference is though that since "" is an actual string, you can still invoke methods or functions on it like

a.length()

a.substring(0, 1)

and so on.

If the String equals null, like b, Java would throw a NullPointerException if you tried invoking, say:

b.length()


If the difference you are wondering about is == versus equals, it's this:

== compares references, like if I went

String a = new String("");
String b = new String("");
System.out.println(a==b);

That would output false because I allocated two different objects, and a and b point to different objects.

However, a.equals(b) in this case would return true, because equals for Strings will return true if and only if the argument String is not null and represents the same sequence of characters.

Be warned, though, that Java does have a special case for Strings.

String a = "abc";
String b = "abc";
System.out.println(a==b);

You would think that the output would be false, since it should allocate two different Strings. Actually, Java will intern literal Strings (ones that are initialized like a and b in our example). So be careful, because that can give some false positives on how == works.

Top answer
1 of 4
2

No, because they are not the same. "" is very different from null.

Now if you want this behavior write a custom method:

static boolean checkIfEmptyOrNull(String s1, String s2) {
     //check for empty and null
     return myBooleanValue;
}

Mark this as static because this should be a helper (and should probably go in a helper class as well)

2 of 4
1

As oracle stores all empty strings as null, we have been mapping the respective columns with a custom data-type that maps all null-values in the database to empty strings. So all Strings read from the database will be empty instead of null.

To create this type you implement a class extending org.hibernate.usertype.UserType;:

import org.hibernate.usertype.UserType;
public class OracleStringType implements UserType {...}

Most required method-implementations are quite straightforward, as you just return the parameter passed in. The most interesting are these:

@Override
public boolean equals(Object arg0, Object arg1) throws HibernateException {
    if(arg0 == null) arg0 = "";
    if(arg1 == null) arg1 = "";
    return arg0.equals(arg1);
}
@Override
public int hashCode(Object arg0) throws HibernateException {
    if(arg0==null) arg0="";
    return arg0.hashCode();
}
@Override
public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner)
        throws HibernateException, SQLException {
    String result = resultSet.getString(names[0]);
    if(resultSet.wasNull()) return "";
    return result;
}

@Override
public void nullSafeSet(PreparedStatement statement, Object value, int index)
        throws HibernateException, SQLException {
    if(value == null) {
        statement.setNull(index, Hibernate.STRING.sqlType());
    } else {
        String valueString = (String)value;
        statement.setString(index, valueString);
    }
}