isEmpty
Some strings exist and are not null
, but have zero characters. We can test for this case with the isEmpty
method.
With isEmpty
, we detect when a string
has a length of 0. We can also test the length()
method for the value 0. And with String
equals()
we can compare an empty string
.
This program uses the isEmpty
method. We declare a string
called "value" and assign it to an empty string
literal.
isEmpty
method returns true. So the inner statements of the if
-block are reached.public class Program { public static void main(String[] args) { String value = ""; // See if string is empty. if (value.isEmpty()) { // Display string length. System.out.println("String is empty, length = " + value.length()); } } }String is empty, length = 0
Equals
, empty stringsWe can compare a string
to see if it is empty with equals()
. We cannot use the equals operator == as this will compare the references identities.
String
equals()
compares the inner characters of a string
. This can correctly tell us if the string
is empty.public class Program { public static void main(String[] args) { String value = ""; // Two equal string literals can be tested for identity. if (value == "") { System.out.println("Test 1"); } // A new empty string will not have the same identity. // ... This test will not succeed. String empty = new String(""); if (value == empty) { System.out.println("Test 2"); // Not reached. } // The equals method tests for character equivalence. // ... This test will succeed. if (value.equals(empty)) { System.out.println("Test 3"); } } }Test 1 Test 3
NullPointerException
We cannot use the isEmpty
method on a null
String
reference. We must first test against null
if the String
reference might be null
.
public class Program { public static void main(String[] args) { String value = null; // This program will not work. if (value.isEmpty()) { System.out.println(0); } } }Exception in thread "main" java.lang.NullPointerException at Program.main(Program.java:6)
I tested the performance of string
equals()
and isEmpty
. The Java runtime is well-optimized. In my simple benchmark, no measurable differences were present.
Empty strings are often present in Java programs. We use them to avoid null
strings, which can cause NullPointerExceptions
.
I feel isEmpty
is the best option, but sometimes testing length()
for values is appropriate. It is rare that using string
equals()
is needed here.