Sub topic 3
Null Versus Empty Text
A Java String can hold empty text, or it can have no string value at all. These are different situations, and your program may need to handle them differently.
Two kinds of “nothing”
A variable is a name that holds a value. A String variable holds a reference, which identifies a string value.
String name = null;meansnamedoes not refer to a string.String name = "";meansnamerefers to an empty string: a string with no text.String name = " ";meansnamerefers to a string containing one space. It is not empty.
The word null has no quotes. With quotes, "null" is ordinary text containing four letters.
A method is an action you can call on a value. The isEmpty() method tells you whether a string has no text. But you cannot call it on null, because there is no string to act on. Trying to do so causes a NullPointerException, an error that stops normal program execution unless it is handled.
Check a value safely
This program checks for null first. Only when it has a string does it call isEmpty().
public class NullAndEmpty {
public static void main(String[] args) {
describe(null);
describe("");
describe(" ");
describe("Ada");
}
static void describe(String text) {
if (text == null) {
System.out.println("No string");
} else if (text.isEmpty()) {
System.out.println("Empty string");
} else {
System.out.println("Not empty; length: " + text.length());
}
}
}Save the program as NullAndEmpty.java. Compile and run it with:
javac NullAndEmpty.java
java NullAndEmptyThe output is:
No string
Empty string
Not empty; length: 1
Not empty; length: 3The test text == null checks whether the variable has no string value. If that test is true, Java skips the later else if test. If it is false, text.isEmpty() is safe to call.
The length() method tells us the length of the string. In these examples, the single space has length 1, and "Ada" has length 3. A space may look blank on the screen, but it still makes the string nonempty.
When should you use each?
Use an empty string when you have text that happens to contain nothing. For example, a person might leave a text box empty. Use null when your program needs to represent the absence of a string value, such as a value that was not provided.
The exact meaning depends on the program. Decide whether the two cases matter separately, and check for them accordingly.
Exercise
What does the program print for describe(" "), and why?
Show answer
It prints Not empty; length: 1 because the string contains one space.
Exercise
Why does the program check text == null before calling text.isEmpty()?
Show answer
Calling isEmpty() on null would cause a NullPointerException. The first check prevents that call.