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
๐ŸŒ
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?
import java.util.Scanner; public class CompringStrings { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter your first string value: "); String str1 = sc.next(); System.out.println("Enter your second string value: "); String str2 = sc.next(); //Comparing two Strings int res = str1.compareTo(str2); System.out.println(res); if(res==0) { System.out.println("Both Strings are null or equal"); }else if(res<0){ System.out.println(""+str1+" preceeds "+str2+""); }else if(res>0){ System.out.println(""+str2+" preceeds "+str1+""); } } }
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java string โ€บ comparing strings in java
Comparing Strings in Java | Baeldung
June 19, 2024 - Also, if any of the two strings is null, then the method returns false. The equalsIgnoreCase() method returns a boolean value. As the name suggests this method ignores casing in characters while comparing Strings: String string1 = "using equals ignore case"; String string2 = "USING EQUALS IGNORE CASE"; assertThat(string1.equalsIgnoreCase(string2)).isTrue();
๐ŸŒ
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)
However, if you set the context parameter javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL to true, the value of the managed bean attribute is passed to the Bean Validation runtime as a null value, causing the @NotNull constraint to fail. ... 48.4.3.4 To Build, Package, and Deploy the hello1-formauth Example Using Maven and the asadmin Command
Find elsewhere
๐ŸŒ
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. Here is an example of how you can check if a string is null:
๐ŸŒ
CodeGym
codegym.cc โ€บ java blog โ€บ strings in java โ€บ java: check if string is null, empty or blank
Java: Check if String is Null, Empty or Blank
October 11, 2023 - Both strings are null. The String = null The String = Lubaina Khan ยท โ€œAn empty String in Java means a String with length equal to zero.โ€ If a String is empty that means the reference variable is referring to a memory location holding a String of length equal to zero.
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?

๐ŸŒ
Stack Abuse
stackabuse.com โ€บ java-check-if-string-is-null-empty-or-blank
Java: Check if String is Null, Empty or Blank
February 28, 2023 - String string = "Hello there"; if (string == null || string.equals("") || string.trim().equals("")) System.out.println("String is null, empty or blank"); else System.out.println("String is neither null, empty nor blank"); In much the same fashion as the before, if the trimmed string is "", ...
๐ŸŒ
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.
๐ŸŒ
Programiz
programiz.com โ€บ java-programming โ€บ examples โ€บ string-empty-null
Java Program to Check if a String is Empty or Null
Java String equals() Java String contains() Java String compareToIgnoreCase() Java String compareTo() To understand this example, you should have the knowledge of the following Java programming topics: Java if...else Statement ยท Java Methods ยท Java String isEmpty() Java String trim() class Main { public static void main(String[] args) { // create null, empty, and regular strings String str1 = null; String str2 = ""; String str3 = " "; // check if str1 is null or empty System.out.println("str1 is " + isNullEmpty(str1)); // check if str2 is null or empty System.out.println("str2 is " + isNullE
๐ŸŒ
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)
For this type of thing I switched it around and did it like "MyValue".equals(myVar), which won't throw an exception if myVar is null. I know that doesn't completely address your particular issue. For your problem, you might want to consider writing a function to handle your comparison, particularly if you do this often in your code. You could go with the try/catch or a couple of if/then statements to check for null before doing the comparison inside the function. ... Assuming your String reference variables are strObj1 and strObj2, you could do the following: -Peter
๐ŸŒ
TechVidvan
techvidvan.com โ€บ tutorials โ€บ java-string-equals-method
Java String equals() Method - TechVidvan
March 18, 2024 - String Literal : It can be applied ... changed to implement unique comparison logic. Null Safety: If you try to use equals() on a null reference, it will return false rather than throwing an exception....
๐ŸŒ
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