I think you might be misremembering or misinterpreting what IntelliJ said. Using == to check whether a string is null is perfectly fine. What you can't do is use == to check whether two non-null strings have the same contents. Answer from sepp2k on reddit.com
🌐
Baeldung
baeldung.com › home › java › java string › comparing strings in java
Comparing Strings in Java | Baeldung
June 19, 2024 - The equals() method of StringUtils class is an enhanced version of the String class method equals(), which also handles null values:
🌐
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 - public class DemoApplication { final static String theStringIknow = "Hello"; public static void myTestMethod(String someString) { //do not do this if (someString.equals(theStringIknow)) { System.out.println("Same same"); } } public static void main(String[] args) { String testString = null; myTestMethod(testString); } }Exception in thread "main" java.lang.NullPointerException at com.example.demo.DemoApplication.myTestMethod(DemoApplication.java:7) at...
🌐
TutorialsPoint
tutorialspoint.com › comparing-strings-with-possible-null-values-in-java
Comparing Strings with (possible) null values in java?
In the same way the equals() method of the object class accepts two String values and returns a boolean value, which is true if both are equal (or, null) and false if not. import java.util.Scanner; public class CompringStrings { public static void main(String args[]) { Scanner sc = new ...
🌐
W3Docs
w3docs.com › java
How to check if my string is equal to null?
To check if a string is equal to null in Java, you can use the == operator.
Find elsewhere
🌐
Coderanch
coderanch.com › t › 387952 › java › avoid-null-pitfalls-comparing-Strings
How do I avoid null pitfalls when comparing Strings? (Beginning Java forum at Coderanch)
If any is then don't do the comparison. If none of them is null, use the eqauls() method to do your comparison. Good luck, Bosun · Bosun (SCJP, SCWCD). So much trouble in the world -- Bob Marley ... The way to compare String object contents is to use the equals() method.
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)
If one is null and other has values,if these are assigned at run time ; how do I compare with equalsIgnoreCase and equals() ? Apparently null is different from any other value,so I HAVE TO EXPECT null and other values in both elements. This happends for only first element. How do I write a refined code for comparing two values considering or expecting null ? if I use the following way,its not correct ... Find the java.util.Objects class, which has equals() methods overloaded to take two parameters, and can cope with null values.
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);
    }
}
🌐
Vultr Docs
docs.vultr.com › java › standard-library › java › lang › String › equals
Java String equals() - Compare Strings Equality
December 23, 2024 - Consequently, the equals() method returns false. Understand that invoking equals() on a null reference will throw a NullPointerException. Perform a null check before using equals() for comparison.
🌐
TechVidvan
techvidvan.com › tutorials › java-string-equals-method
Java String equals() Method - TechVidvan
March 18, 2024 - Custom Comparison: You can design ... perform unique equality checks catered to the needs of your application. Handling Nulls:Calling equals() on a string that might be null is secure....
🌐
Oracle
docs.oracle.com › javaee › 7 › tutorial › bean-validation002.htm
21.2 Validating Null and Empty Strings - Java Platform, Enterprise Edition: The Java EE Tutorial (Release 7)
The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all.
🌐
JoeHx Blog
joehxblog.com › does-null-equal-null-in-java
Does Null Equal Null in Java? – JoeHx Blog
October 31, 2018 - Since I’m dealing with null objects, the normal Object.equals(Object other) is unavailable to me. I can only use the simple equality operator (the double-equals “==”) or some helper methods, such as Objects.equals(Object, Object). Which is what I did. Below is the short but beautiful Java program I wrote: import java.util.Objects; public class Main { public static void main(final String[] args) { System.out.println("true: " + true); System.out.println("false: " + false); System.out.println(); final String string = null; final Number number = null; System.out.println("null == null: " + (n
🌐
Reddit
reddit.com › r/learnjava › best way to check for null on strings?
Best way to check for null on Strings? : r/learnjava
May 8, 2024 - Plus "someString == null" will always be false since the result of String.valueOf will never be null. edit after reading josephblade's answer : +1 on the "optional is probably not what you want". ... I think StringUtil.isEmpty will check if it's "" or null. It might be .isBlank I can't remember. Edit. Misread your question. Imo it's · return someString.equals("null") || Objects.isNull(some string) ?