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 ...
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 I were checking for a particular constant, I could just do "Joe".equals(name). But either argument could be null in my case. Any ideas would be appreciated, Thanks, Jason. ... Why don't you check if any of the values/variables are false? 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.
🌐
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.
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.
🌐
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....
🌐
How to do in Java
howtodoinjava.com › home › string › java string.equals()
Java String.equals() with Examples - HowToDoInJava
January 9, 2023 - String str1 = "alex"; Assertions.assertThrows(NullPointerException.class, () -> { str1.contains(null); }); The following Java program demonstrates that equals() method does the content comparison in a case-sensitive manner.
🌐
Qlik Community
community.qlik.com › t5 › Talend-Studio › Handling-nulll-while-doing-equals-function › td-p › 2326825
Handling nulll while doing equals function - Qlik Community - 2326825
February 4, 2017 - As we know equals function (var1.equals(var2)) does not handle null values and it thows "null pointer exception ".In other words , both variables should have values only then it can work .If I used two equals function (==) function It is not ...