In this tutorial, we’ll take a look at the difference between null and empty String in Java. These are two distinct concepts, but sometimes they may not be used as intended with Strings.
2. null String in Java
null is a reserved keyword in Java that signifies the absence of any value. Moreover, assigning a null value to an object reference implies that it doesn’t refer to any object or value in the memory.
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.
3. Empty String in Java
An empty String is a valid String object having no characters, and as a result, all the String operations are available on this object.
Let’s take a look at some tests to see the difference between the two:
String nullString = null; String emptyString = ""; assertTrue(emptyString.equals("")); assertThrows(NullPointerException.class, () -> nullString.length());
In the above test case, we defined two String objects, one empty and one null. Then we tried to use the methods available in the String class.
The test case executes successfully and thus verifies that the String operations are available for an empty String, but not for a null String.
Let’s check another scenario where we check for equality of the two:
String nullString = null; String emptyString = ""; assertFalse(emptyString.equals(nullString)); assertFalse(emptyString == nullString);
In this test scenario, we are comparing whether the two String objects are equal using equals() and ==. Upon executing the test case, it successfully verifies that null and empty String aren’t the same.
In this article, we’ve learned the difference between null and empty String in Java. First, we defined the concepts and then saw how they behaved in different scenarios.
In essence, null represents the absence of any value, whereas an empty String represents a valid String. The empty String has some value whose length is zero.
As usual, the source code for all the examples can be found over on GitHub.