Copyif (myString != null && !myString.isEmpty()) {
  // doSomething
}

As further comment, you should be aware of this term in the equals contract:

From Object.equals(Object):

For any non-null reference value x, x.equals(null) should return false.

The way to compare with null is to use x == null and x != null.

Moreover, x.field and x.method() throws NullPointerException if x == null.

Answer from polygenelubricants on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › program-to-check-if-the-string-is-null-in-java
Program to check if the String is Null in Java - GeeksforGeeks
July 12, 2025 - The below example demonstrates how to check if a given string is null using the == relational operator. ... // Java Program to check if // a String is Null class StringNull { // Method to check if the String is Null public static boolean ...
🌐
Reddit
reddit.com › r/java › cleanest way to check for null on a string?
Cleanest way to check for null on a String? : r/java
May 8, 2024 - D is correct by chance : you switch the String.valueOf() call to obj.toString and I had to look the doc "if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned." If it was a pure replacement I would raise an eyebrow during code review, but that code is 100% correct. [EDIT] Why are you even converting unknown type of elements into String? In real-life situations, I would recheck the requirements. ... News, Technical discussions, research papers and assorted things of interest related to the Java programming language NO programming help, NO learning Java related questions, NO installing or downloading Java questions, NO JVM languages - Exclusively Java
🌐
Programiz
programiz.com › java-programming › examples › string-empty-null
Java Program to Check if a String is Empty or Null
This is because white spaces are treated as characters in Java and the string with white spaces is a regular string. Now, if we want the program to consider strings with white spaces as empty strings, we can use the trim() method. The method removes all the white spaces present in a string. class Main { public static void main(String[] args) { // create a string with white spaces String str = " "; // check if str1 is null or empty System.out.println("str is " + isNullEmpty(str)); } // method check if string is null or empty public static String isNullEmpty(String str) { // check if string is null if (str == null) { return "NULL"; } // check if string is empty else if (str.trim().isEmpty()){ return "EMPTY"; } else { return "neither NULL nor EMPTY"; } } }
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:

String 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:

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

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

String 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:

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

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

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

boolean 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
s == 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 "", it was either empty from the get-go, or was a blank string with 0..n whitespaces: ... The Apache Commons is a popular Java library that provides further functionality.
🌐
Baeldung
baeldung.com › home › java › java string › checking for empty or blank strings in java
Checking for Empty or Blank Strings in Java | Baeldung
January 8, 2024 - String#isEmpty was introduced with Java 6. For Java 5 and below, we can use String#length instead: boolean isEmptyString(String string) { return string == null || string.length() == 0; } In fact, String#isEmpty is just a shortcut to String#length.
Find elsewhere
🌐
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 - Java provides a built-in method to check for all those whitespaces in a String. Let’s look at an example on how to use that. public class Example2 { public static void main(String[] args) { // check if it is a "blank" string String myName = new String(" \t \n \t \t "); System.out.println("The String = " + myName); System.out.println("Is the String null?
🌐
Medium
medium.com › @ecetasci.iu › checking-for-null-or-empty-strings-in-java-19518fa1e553
Checking for Null or Empty Strings in Java | by Ece Tasci | Medium
February 25, 2025 - In Java, calling a method on a null reference will result in a NullPointerException, one of the most common runtime errors. To prevent this, it is crucial to check for null before performing operations on a variable. An empty String ("") has zero characters but still exists in memory, specifically in the heap where Java stores objects.
🌐
Vultr Docs
docs.vultr.com › java › examples › check-if-a-string-is-empty-or-null
Java Program to Check if a String is Empty or Null | Vultr Docs
December 17, 2024 - Here, StringUtils.isBlank() checks if str is null, empty, or made solely of whitespace (spaces, tabs, new line characters). Very useful when the mere presence of whitespace should also classify the string as "empty". Recognize the enhancements in Java 11 including new String methods.
🌐
Quora
quora.com › How-do-perform-a-Null-check-for-string-in-Java
How do perform a Null check for string in Java? - Quora
Answer (1 of 7): 4 Ways to check if String is null or empty in Java:- Here are my four solutions for this common problem. Each solution has their pros and cons and a special use case e.g. first solution can only be used from JDK7 on wards, second solution is the fastest way to check string is em...
🌐
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)
if (testString==null) { doSomething(); } else { doAnotherThing(); } By default, the doAnotherThing method is called even when the user enters no data, because the testString element has been initialized with the value of an empty string. In order for the Bean Validation model to work as intended, ...
🌐
Javatpoint
javatpoint.com › how-to-check-null-in-java
How to Check null in Java
How to Check null in Java with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods, examples etc.
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
April 8, 2019 - So, if an API accepts multiple parameters that aren’t allowed to be null, it’s better to check for every non-null parameter as a precondition of the API. Let’s look at two methods — one that fails early and one that doesn’t: public void goodAccept(String one, String two, String three) { if (one == null || two == null || three == null) { throw new IllegalArgumentException(); } process(one); process(two); process(three); } public void badAccept(String one, String two, String three) { if (one == null) { throw new IllegalArgumentException(); } else { process(one); } if (two == null) { throw new IllegalArgumentException(); } else { process(two); } if (three == null) { throw new IllegalArgumentException(); } else { process(three); } }
🌐
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.
🌐
TutorialsPoint
tutorialspoint.com › check-if-a-string-is-empty-or-null-in-java
Check if a String is empty ("") or null in Java
Practice 3500+ coding problems and tutorials. Master programming challenges with problems sorted by difficulty. Free coding practice with solutions.
🌐
Coderanch
coderanch.com › t › 693624 › java › check-null-empty-strings-time
Do we have any way to check null value and empty strings all the time ? (Features new in Java 8 forum at Coderanch)
Remember the zero‑length String is different from null. Is there any feature of an Optional<String> that you could use? Look at this article by Urma. ... Hi, Why not write a program to do the job, and then simply call this program with the variable arguments? Here is an example. The Consumer<String> process is your actual program. The rest is just testing environment: ... Yes, Means in programming we need to check null values every time to save program from the null exception while execution.
🌐
BeginnersBook
beginnersbook.com › 2022 › 10 › check-if-string-is-null-empty-or-blank-in-java
Check if String is Null, Empty or Blank in Java
Simply compare the string with null to check for null string. Use isEmpty() method of string class to check for empty string. The isEmpty() method returns true if the string does not contain any value. Use trim() and isEmpty() method together to check for blank string.