Correct way to check for null or empty or string containing only spaces is like this:

if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }
Answer from Pradeep Simha on Stack Overflow
🌐
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 - Like Guava, it won’t check if a string only contains whitespace but checks whether a given string is null or empty. There are several ways to check whether a string is empty or not. Often, we also want to check if a string is blank, meaning that it consists of only whitespace characters. The most convenient way is to use Apache Commons Lang, which provides helpers such as StringUtils.isBlank. If we want to stick to plain Java, we can use a combination of String#trim with either String#isEmpty or String#length.
Discussions

Java: difference between String a = null and String a = new String() - Software Engineering Stack Exchange
In your case perhaps the empty string "" would be a good default value if you want to avoid NullPointerException. In the other hand, sometimes it is desirable that the program produce an exception because it indicates something wrong happened under the hood that should not have happened. ... Agreed. But also, if the OP doesn't need to change s, they should initialize it once and make it final. No need to mess with null or ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
July 27, 2015
Should I use 'null' or empty string?
It depends on how you are going to use the variable. Sometimes you need to distinguish between an empty string and a string which hasn't been assigned a value, in which case using an empty string probably will not work. More on reddit.com
🌐 r/learnprogramming
7
1
October 10, 2018
Does it make sense to initialize a string as null instead of as an empty string?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
16
6
January 15, 2023
Cleanest way to check for null on a String?
If all you're doing is returning an Optional, use the features of the Optional: return Optional.ofNullable(someObject.get("someKey")); If you need to do some additional processing on the string value, call .map() on the Optional. More on reddit.com
🌐 r/java
11
3
May 8, 2024
🌐
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.
🌐
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 - public static boolean isNullOrEmpty(String str) { return str == null || str.isBlank(); } Explain Code · With Java 11, String.isBlank() does what StringUtils.isBlank() from Apache Commons does but without the need for an external library. Checking if a string is empty or null in Java can be approached in multiple ways, each serving different needs depending on your project requirements.
🌐
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 - 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.
🌐
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 - 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.
🌐
Codemia
codemia.io › knowledge-hub › path › checking_if_a_string_is_empty_or_null_in_java
Checking if a string is empty or null in Java
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
Find elsewhere
🌐
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)
An empty string is represented as "". It is a character sequence of zero characters. A null string is represented by null. It can be described as the absence of a string instance. Managed bean elements represented as a JavaServer Faces text component such as inputText are initialized with the ...
🌐
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
January 7, 2023 - 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.
🌐
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...
🌐
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. ...
Top answer
1 of 3
11

First let's clarify something: You mention that after assigning null to the variable you could forget to initialize it, but by assigning null to it you are in effect initializing it.

public static void main (String args[]){
    String s;       
    System.out.println(s); // compiler error variable may not be initialized
}

vs

public static void main (String args[]){
    String s=null;      
    System.out.println(s); // no compiler error
    System.out.println(s.equals("helo")); // but this will generate an exception
}

So after you do String s=null; there's is no way that you could forget to initialize because you did initialize it.

That being clear, I would recommend you to use a "smart default". In your case perhaps the empty string "" would be a good default value if you want to avoid NullPointerException. In the other hand, sometimes it is desirable that the program produce an exception because it indicates something wrong happened under the hood that should not have happened.

2 of 3
8

In general you want to keep declaration and initialisation as close as possible to minimise exactly the type of problem you're talking about.

There is also the issue of redundant initialisation where the value null you're assigning is never used which is extra code that harms readability even if the redundant assignment is optimised away by the compiler.

Sometimes assigning some sort of default value is unavoidable, for example if you declare before a try catch, initialise inside and use it afterwards. For other types you can often find a more natural default value such as an empty list.

🌐
Mkyong
mkyong.com › home › java › java – check if a string is empty or null
Java - Check if a String is empty or null - Mkyong.com
April 29, 2019 - In Java, we can use (str != null && !str.isEmpty()) to make sure the String is not empty or null.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.string.isnullorempty
String.IsNullOrEmpty(String) Method (System) | Microsoft Learn
Class Sample Public Shared Sub ...llOrEmpty(s) Then Return "is null or empty" Else Return String.Format("(""{0}"") is neither null nor empty", s) End If End Function End Class ' The example displays the following output: ' String ...
🌐
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 - But as an FYI instead of "String.valueOf" you can use "java.util.Objects.toString(Object o, String nullDefault)" instead, which was added in Java 1.7. If you replaced String.valueOf(someObject.get("someKey")) with Objects.toString(someObject.get("someKey"), null) then it works just fine when the result is null. ... return switch(m.get("someKey") ) { case null -> Optional.empty(); case Object o -> Optional.of(String.valueOf(o)); };
🌐
TestMu AI Community
community.testmuai.com › ask a question
Best Way to Check if a String is Null or Empty in Java - TestMu AI Community
March 19, 2025 - What is the best way to check if a String is null or empty in Java? I’m currently parsing HTML data, and sometimes the String can be null or empty when the expected word doesn’t match. To handle this, I wrote the following check: if(string.equals(null) || string.equals("")){ Log.d("iftrue", "seem to be true"); }else{ Log.d("iffalse", "seem to be false"); } However, when I remove string.equals(""), the condition doesn’t work correctly.
🌐
W3Schools
w3schools.com › java › ref_string_isempty.asp
Java String isEmpty() Method
This method returns true if the string is empty (length() is 0), and false if not. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an ...
🌐
WsCube Tech
wscubetech.com › resources › java › programs › string-empty-null
Java Program to Check if a String is Empty or Null (4 Programs)
October 17, 2025 - Learn 4 simple ways to check if a string is empty or null in Java. Explore easy-to-understand programs using if-else, the ternary operator, and more. Read now!