Sub topic 3
Null Versus Empty Text
A Java program often needs to tell the difference between text that has no characters and text that is missing. Java uses an empty string for the first case and null for the second.
The difference matters when you check input, show a message, or pass a value to another part of a program. If you treat null like a string, your program can stop with an error.
Two different states
A string is a value that holds text. A variable is a named place that holds a value. For example, String name = "Ada"; creates a variable named name that refers to a string.
An empty string is a string with zero characters. You write it as "". It is still a string, so you can ask for its length or check whether it is empty.
null is a special Java value that means a variable does not refer to an object. An object is a value created from a Java class, such as a String. A variable that is null does not refer to a string at all.
| Value | Meaning | Is there a string? |
|---|---|---|
| `null` | No string is present | No |
| `""` | A string with zero characters | Yes |
| `" "` | A string with one space | Yes |
| `"null"` | A string with four letters | Yes |
The word null inside quotes is ordinary text. Without quotes, null is the special Java value.
A variable is not automatically empty when you declare it inside a method. You must give it a value before you use it. For example, you can start it with null if no string is present yet.
Why the difference matters
Think of a form with a note field:
nullcould mean the program did not receive a note.""could mean the program received a note, but the note has no characters." "could mean the program received a space.
Those meanings depend on the rules of the program. Some programs use an empty string to mean missing input. Others need to keep missing and empty values separate. Decide what each value means before choosing how to handle it.
For example, a missing note might mean “leave the old note as it is,” while an empty note might mean “clear the old note.” If you change every null into "", you lose that distinction.
Checking for null and empty
A method is a named action that code can call. String methods such as isEmpty() and length() need a string to work on.
Use == null to check whether a variable has no value. Use isEmpty() to check whether an existing string has zero characters.
Check for null first. Calling isEmpty() on a null variable causes a NullPointerException. An exception is a problem that interrupts the normal flow of a program.
The following program checks for missing, empty, and blank text. It needs Java 11 or later because it uses isBlank().
class NullAndEmptyDemo {
static void describe(String text) {
if (text == null) {
System.out.println("Missing");
} else if (text.isEmpty()) {
System.out.println("Empty");
} else if (text.isBlank()) {
System.out.println("Blank, but not empty");
} else {
System.out.println("Other text");
}
}
public static void main(String[] args) {
describe(null);
describe("");
describe(" ");
describe("Ada");
describe("null");
}
}Save the code in a file named NullAndEmptyDemo.java. Then compile and run it:
javac NullAndEmptyDemo.java
java NullAndEmptyDemoThe output is:
Missing
Empty
Blank, but not empty
Other text
Other textThe first check handles null. Only when that check is false does the program call isEmpty(). Only when the string is not empty does it call isBlank().
A blank string contains no visible text according to Java's whitespace rules. Spaces and tabs are examples of whitespace. isBlank() also returns true for an empty string, so the order of the checks matters when you want to report “empty” separately from “blank, but not empty.”
Checking safely in one condition
Sometimes you want to know whether a string is both present and nonempty. Java lets you combine those checks with &&, which means “and.”
The program below uses a method named hasText. It returns a boolean, a value that is either true or false.
class SafeTextCheck {
static boolean hasText(String text) {
return text != null && !text.isEmpty();
}
public static void main(String[] args) {
System.out.println(hasText(null));
System.out.println(hasText(""));
System.out.println(hasText(" "));
System.out.println(hasText("Ada"));
}
}Save it as SafeTextCheck.java, then run it with javac SafeTextCheck.java and java SafeTextCheck. The output is:
false
false
true
trueRead the condition from left to right:
text != nullchecks that a string is present. The symbol!=means “is not equal to.”&&requires both checks to be true.!text.isEmpty()checks that the string is not empty. The!means “not.”
Java does not run the right side of && when the left side is false. This is called short-circuiting. When text is null, the first check is false, so Java does not call isEmpty().
The order is important. If you put !text.isEmpty() first, Java would try to call it on null before it checked for null.
Notice that hasText(" ") returns true: a space is not empty. If your rule is “must contain nonblank text,” use !text.isBlank() after the null check instead.
Common mistakes
Treating a space as empty
"" has zero characters. " " has one character: a space. Both may look blank when printed, but only the first is empty.
Calling a method before checking for null
A condition such as text.isEmpty() is safe only when text refers to a string. Check text == null first, or use a short-circuit condition with the null check on the left.
Using an empty-string check as a null check
isEmpty() answers whether an existing string has zero characters. It does not answer whether the variable is null. The two checks answer different questions.
Use == null for the null check. Do not use == "" to test whether a string is empty; use isEmpty() on a known non-null string.
Trusting printed output alone
Printing a String variable whose value is null displays null. Printing the string "null" also displays null. The output can therefore look the same even though the values are different.
When debugging, check whether the variable is null rather than deciding from its printed text alone.
Practice
Exercise
A variable contains "". Is it null, empty, or both? What does isEmpty() return?
Show answer
It is empty, not null. It refers to a string, and isEmpty() returns true.
Exercise
Why is text != null && !text.isEmpty() safe when text is null?
Show answer
The first check is false, so Java skips the call to isEmpty() on the right.
Exercise
A form receives " " as a note. Is it empty? Would the hasText method above accept it?
Show answer
It is not empty because it contains a space. The method accepts it, though isBlank() would identify it as blank.