You may also understand the difference between null and an empty string this way:

Original image by R. Sato (@raysato)

Answer from mikiqex on Stack Overflow
Top answer
1 of 16
408

You may also understand the difference between null and an empty string this way:

Original image by R. Sato (@raysato)

2 of 16
251

"" is an actual string, albeit an empty one.

null, however, means that the String variable points to nothing.

a==b returns false because "" and null do not occupy the same space in memory--in other words, their variables don't point to the same objects.

a.equals(b) returns false because "" does not equal null, obviously.

The difference is though that since "" is an actual string, you can still invoke methods or functions on it like

a.length()

a.substring(0, 1)

and so on.

If the String equals null, like b, Java would throw a NullPointerException if you tried invoking, say:

b.length()


If the difference you are wondering about is == versus equals, it's this:

== compares references, like if I went

String a = new String("");
String b = new String("");
System.out.println(a==b);

That would output false because I allocated two different objects, and a and b point to different objects.

However, a.equals(b) in this case would return true, because equals for Strings will return true if and only if the argument String is not null and represents the same sequence of characters.

Be warned, though, that Java does have a special case for Strings.

String a = "abc";
String b = "abc";
System.out.println(a==b);

You would think that the output would be false, since it should allocate two different Strings. Actually, Java will intern literal Strings (ones that are initialized like a and b in our example). So be careful, because that can give some false positives on how == works.

🌐
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
🌐
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"; } } }
🌐
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 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.

🌐
Baeldung
baeldung.com › home › java › java string › difference between null and empty string in java
Difference Between null and Empty String in Java | Baeldung
April 19, 2024 - By default, Java initializes reference variables with null values and primitives with default values based on their type. As a result, we cannot assign null to primitives. If we assign null to a String object, it’s initialized but not instantiated and hence holds no value or reference.
🌐
Coderanch
coderanch.com › t › 522022 › java › parse-null-string-null
How to parse null string to null. (Beginning Java forum at Coderanch)
Try changing equals to equalsIgnoreCase, so you can pass "null" "Null" or "NULL". Otherwise it looks perfectly good to me. You are lacking a semicolon and you have an unmatched ) right round bracket/parenthesis. Why do you want to introduce nulls into your application in the first place?
🌐
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 - In Java, checking if a string is null is essential for handling null-safe conditions and preventing runtime errors. To check if a string is null in Java, we can use the "==" operator that directly compares the string reference with null. ... The below example demonstrates how to check if a given string is null using the == relational operator.
Find elsewhere
🌐
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
🌐
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.
🌐
DataCamp
datacamp.com › doc › java › null
null Keyword in Java: Usage & Examples
public class NullExample { public static void main(String[] args) { String str = null; if (str == null) { System.out.println("The string is null."); } } } In this example, the String variable str is initialized to null.
🌐
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
String myString = ""; //empty string if(myString!=null && myString.isEmpty()){ System.out.println("This is an empty string"); } A blank string contains only whitespaces. String str = " "; //there is a whitespace between quotes · The length of a blank string is not zero, the isEmpty() method ...
🌐
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 "", ...
🌐
Medium
medium.com › 360learntocode › example-to-test-whether-string-is-null-or-empty-in-java-7091166b2ace
Example to Test Whether String is Null or Empty in Java | by kumar chapagain | 360learntocode | Medium
March 10, 2025 - public class StringUtil { public static void main(String[] args) { String nonEmptyString = "non empty string"; String nullString = null; String emptyString = ""; String emptyStringWithWhiteSpace = " "; boolean isNonEmpty = isNullOrEmpty(nonEmptyString); System.out.println(isNonEmpty); //false boolean isNullString = isNullOrEmpty(nullString); System.out.println(isNullString); //true boolean isEmptyString = isNullOrEmpty(emptyString); System.out.println(isEmptyString); //true boolean isEmptyStringWithWhiteSpace = isNullOrEmpty(emptyStringWithWhiteSpace); System.out.println(isEmptyStringWithWhiteSpace); //true } private static boolean isNullOrEmpty(String str) { if(str == null || str.trim().isEmpty()) return true; return false; } }
🌐
Java67
java67.com › 2014 › 09 › right-way-to-check-if-string-is-empty.html
Right way to check if String is empty in Java with Example | Java67
It has methods like isEmpty() which return true for both null and empty string literal. Again this is also null safe and will not throw NullPointerException. By the way, if you are new to Java Programming then I also suggest you check out a comprehensive Java course like The Complete Java Masterclass course by Tim Buchalka and his team on Udemy. This 80-hour long course is well structured and covers all essential Java concepts to learn Java from scratch. Here are a couple of examples of testing for String emptiness without worrying about null inputs.
🌐
Delft Stack
delftstack.com › home › howto › java › difference between null and empty strings in java
Null and Empty String in Java | Delft Stack
October 12, 2023 - We used the equals() method and equal == operator to check the empty and null string in this example. The expression a==b will return false because "" and null do not occupy the same space in memory.
🌐
LabEx
labex.io › tutorials › java-how-to-handle-null-values-when-joining-java-strings-417590
How to handle null values when joining Java strings | LabEx
This practical example shows how the techniques we've learned can be applied to real-world scenarios. The code is robust and handles null values gracefully, providing default text ("Not provided") when information is missing. In this lab, you have learned how to handle null values when joining Java strings...
🌐
Blogger
javarevisited.blogspot.com › 2016 › 01 › how-to-check-if-string-is-not-null-and-empty-in-java-example.html
How to check if String is not null and empty in Java? Example
Since we are first doing a null check and then an empty check using the && operator, which is a short circuit AND operator. This operator will not check for emptiness if String is null hence no NPE. This is also a good trick to avoid NPE in Java. Btw, you must be careful with the order you carry the null and emptiness check. For example, if you reverse the order of checks i.e.