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)
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 value of the empty string by the JavaServer Faces implementation.
๐ŸŒ
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.
๐ŸŒ
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 isStringNull(String s) { // Compare the string with null // using == relational operator // and return the result if (s == null) return true; else return false; } // Driver code public static void main(String[] args) { // Test strings String s1 = "GeeksforGeeks"; String s2 = null; System.out.println("Is string [" + s1 + "] null?
๐ŸŒ
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 - These are two distinct concepts, but sometimes they may not be used as intended with Strings. null is a reserved keyword in Java that signifies the absence of any value.
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.

๐ŸŒ
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
Find elsewhere
๐ŸŒ
Programiz
programiz.com โ€บ java-programming โ€บ examples โ€บ string-empty-null
Java Program to Check if a String is Empty or Null
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 " + isNullEmpty(str2)); // check if str3 is null or empty System.out.println("str3 is " + isNullEmpty(str3)); } // 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
Top answer
1 of 3
1

Assign null

When we write:

String s = "Hello World!";
s = null;

The String object still exists in memory because this does not delete it. However the garbage collector will clear the object from memory as there is no variable referencing it.
For all practical purposes s = null; deletes the String.

2 of 3
0

tl;dr

set a String to null in Java?

myString = null ;

declare the variable without initializing it

Uninitialized deaults to null, no String object. Empty reference variable.

String myString ;  

You can explicitly assign null. Same effect as line above. No object, empty reference.

String name = null;

Declare and initialize to empty string:

String myString = "" ;  // A `String` object containing no characters. Not null.

Details

Before posting here on basic Java Questions, study the Java Tutorials provided by Oracle free of cost.

See the tutorial page on string literals. To quote:

There's also a special null literal that can be used as a value for any reference type. null may be assigned to any variable, except variables of primitive types. There's little you can do with a null value beyond testing for its presence. Therefore, null is often used in programs as a marker to indicate that some object is unavailable.

So null is not a piece of text with four characters. The keyword null means โ€œno object at allโ€, no String, nothing at all, an empty reference.

To test if an object reference variable is null (contains no reference), you have a few choices:

  • Objects.isNull( myVar ) and Objects.nonNull( myVar )
  • null == myVar and null != myVar
  • myVar == null and myVar != null

I prefer the first, as words are easier to read than mathematical-like symbols.

๐ŸŒ
DataCamp
datacamp.com โ€บ doc โ€บ java โ€บ null
null Keyword in Java: Usage & Examples
The null keyword in Java is a literal that represents a null reference, one that points to no object. It is often used to indicate that a reference variable does not currently refer to any object or that a method has no return value. The null keyword can be assigned to any reference type variable, ...
๐ŸŒ
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.
๐ŸŒ
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
In Java, null is a special value that indicates the absence of a reference. Variables of reference types (like String, arrays, and custom objects) can be assigned null to indicate they do not refer to any object.
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 522022 โ€บ java โ€บ parse-null-string-null
How to parse null string to null. (Beginning Java forum at Coderanch)
Yes this is the code I currently use. I am convinced I have seen some method once, that does the same thing. Perhaps it was in the Apache commons library. We allow users of our custom logging application to provide a "null" string in a property file, to express they actually mean null (no value).
๐ŸŒ
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"); }
๐ŸŒ
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 - If weโ€™re at least on Java 6, then the simplest way to check for an empty string is String#isEmpty: boolean isEmptyString(String string) { return string.isEmpty(); } To make it also null-safe, we need to add an extra check: boolean isEmptyString(String string) { return string == null || string.isEmpty(); } String#isEmpty was introduced with Java 6.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ interesting-facts-about-null-in-java
Interesting facts about null in Java - GeeksforGeeks
September 3, 2024 - In Java, null is a special value that represents the absence of a value or reference. It is used to indicate that a variable or object does not currently have a value assigned to it.
Top answer
1 of 11
47

If null is a reasonable input parameter for your method, fix the method. If not, fix the caller. "Reasonable" is a flexible term, so I propose the following test: How should the method hande a null input? If you find more than one possible answer, then null is not a reasonable input.

2 of 11
22

Don't use null, use Optional

As you've pointed out, one of the biggest problems with null in Java is that it can be used everywhere, or at least for all reference types.

It's impossible to tell that could be null and what couldn't be.

Java 8 introduces a much better pattern: Optional.

And example from Oracle:

String version = "UNKNOWN";
if(computer != null) {
  Soundcard soundcard = computer.getSoundcard();
  if(soundcard != null) {
    USB usb = soundcard.getUSB();
    if(usb != null) {
      version = usb.getVersion();
    }
  }
}

If each of these may or may not return a successful value, you can change the APIs to Optionals:

String name = computer.flatMap(Computer::getSoundcard)
    .flatMap(Soundcard::getUSB)
    .map(USB::getVersion)
    .orElse("UNKNOWN");

By explicitly encoding optionality in the type, your interfaces will be much better, and your code will be cleaner.

If you are not using Java 8, you can look at com.google.common.base.Optional in Google Guava.

A good explanation by the Guava team: https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained

A more general explanation of disadvantages to null, with examples from several languages: https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/


@Nonnull, @Nullable

Java 8 adds these annotation to help code checking tools like IDEs catch problems. They're fairly limited in their effectiveness.


Check when it makes sense

Don't write 50% of your code checking null, particularly if there is nothing sensible your code can do with a null value.

On the other hand, if null could be used and mean something, make sure to use it.


Ultimately, you obviously can't remove null from Java. I strongly recommend substituting the Optional abstraction whenever possible, and checking null those other times that you can do something reasonable about it.