Introduction
In this lab, you will learn essential techniques for handling null strings in Java. We will begin by exploring the fundamental method of checking for null using the equality operator (==), understanding why this is crucial to prevent NullPointerException.
Building upon this, you will learn how to combine null checks with checks for empty strings to handle various string states effectively. Finally, we will introduce the Optional class as a modern and safer approach to managing potentially null values, demonstrating how it can improve code readability and prevent common errors.
Test for Null Using Equality Operator
In this step, we will learn how to check if a string variable in Java is null using the equality operator (==). Understanding how to handle null is crucial in Java programming to prevent errors.
In Java, a variable of a reference type (like String) can hold a special value called null. This means the variable doesn't refer to any object in memory. Trying to use a null variable as if it were a valid object will result in a NullPointerException, which is a common and frustrating error for beginners.
The simplest way to check if a string is null is by using the equality operator (==).
Let's create a simple Java program to demonstrate this.
Open the WebIDE and make sure you are in the
~/projectdirectory. You can confirm this by looking at the terminal prompt or by typingpwdand pressing Enter.Create a new Java file named
NullCheck.javain the~/projectdirectory. You can do this by right-clicking in the File Explorer on the left, selecting "New File", and typingNullCheck.java.Open the
NullCheck.javafile in the editor and paste the following code:public class NullCheck { public static void main(String[] args) { String myString1 = "Hello"; String myString2 = null; String myString3 = ""; // This is an empty string, not null System.out.println("Checking myString1:"); if (myString1 == null) { System.out.println("myString1 is null"); } else { System.out.println("myString1 is not null"); } System.out.println("\nChecking myString2:"); if (myString2 == null) { System.out.println("myString2 is null"); } else { System.out.println("myString2 is not null"); } System.out.println("\nChecking myString3:"); if (myString3 == null) { System.out.println("myString3 is null"); } else { System.out.println("myString3 is not null"); } } }In this code:
- We declare three
Stringvariables:myString1is assigned a regular string,myString2is explicitly assignednull, andmyString3is assigned an empty string (""). - We use an
ifstatement with the equality operator (==) to check if each string isnull. - We print a message indicating whether the string is
nullor not.
- We declare three
Save the
NullCheck.javafile (Ctrl+S or Cmd+S).Open the Terminal at the bottom of the WebIDE. Make sure you are in the
~/projectdirectory.Compile the Java program using the
javaccommand:javac NullCheck.javaIf there are no errors, this command will create a
NullCheck.classfile in the same directory.Run the compiled Java program using the
javacommand:java NullCheckYou should see output similar to this:
Checking myString1: myString1 is not null Checking myString2: myString2 is null Checking myString3: myString3 is not null
This output confirms that myString1 and myString3 are not null, while myString2 is null. It's important to note the difference between a null string and an empty string (""). An empty string is a valid String object with zero characters, while a null string variable doesn't point to any object.
Using == null is the standard and correct way to check if a reference variable is null in Java.
Combine Null and Empty Checks
In the previous step, we learned how to check if a string is null. However, in many real-world scenarios, you might also need to check if a string is empty (has zero characters) or contains only whitespace. A string that is null, empty, or contains only whitespace is often considered "blank" or "effectively empty".
Checking for both null and empty strings is a common requirement. You can combine these checks using the logical OR operator (||).
Let's modify our previous program to include checks for both null and empty strings.
Open the
NullCheck.javafile in the WebIDE editor.Modify the
mainmethod to include an empty string and combine the checks. Replace the existingmainmethod with the following code:public class NullCheck { public static void main(String[] args) { String myString1 = "Hello"; String myString2 = null; String myString3 = ""; // This is an empty string String myString4 = " "; // This string contains only whitespace System.out.println("Checking myString1:"); if (myString1 == null || myString1.isEmpty()) { System.out.println("myString1 is null or empty"); } else { System.out.println("myString1 is not null and not empty"); } System.out.println("\nChecking myString2:"); if (myString2 == null || myString2.isEmpty()) { System.out.println("myString2 is null or empty"); } else { System.out.println("myString2 is not null and not empty"); } System.out.println("\nChecking myString3:"); if (myString3 == null || myString3.isEmpty()) { System.out.println("myString3 is null or empty"); } else { System.out.println("myString3 is not null and not empty"); } System.out.println("\nChecking myString4:"); // Note: isEmpty() does not check for whitespace if (myString4 == null || myString4.isEmpty()) { System.out.println("myString4 is null or empty"); } else { System.out.println("myString4 is not null and not empty"); } } }In this updated code:
- We added
myString4which contains only whitespace. - We use the condition
myString == null || myString.isEmpty()to check if a string is eithernullor empty. TheisEmpty()method is a built-inStringmethod that returnstrueif the string has a length of 0. - Important: The
isEmpty()method can only be called on a non-null string. If you try to callisEmpty()on anullstring, you will get aNullPointerException. Therefore, it is crucial to check fornullfirst usingmyString == nullbefore callingmyString.isEmpty(). The logical OR operator (||) is "short-circuiting", meaning if the first condition (myString == null) is true, the second condition (myString.isEmpty()) is not evaluated, preventing theNullPointerException.
- We added
Save the
NullCheck.javafile.Compile the modified program in the Terminal:
javac NullCheck.javaRun the compiled program:
java NullCheckYou should see output similar to this:
Checking myString1: myString1 is not null and not empty Checking myString2: myString2 is null or empty Checking myString3: myString3 is null or empty Checking myString4: myString4 is not null and not empty
Notice that myString4 (which contains only whitespace) is considered "not null and not empty" by this check. If you need to also consider strings with only whitespace as "blank", you can use the isBlank() method (available since Java 11).
Let's quickly update the code to use isBlank() for myString4:
Modify the check for
myString4inNullCheck.java:// ... (previous code) ... System.out.println("\nChecking myString4 with isBlank():"); if (myString4 == null || myString4.isBlank()) { System.out.println("myString4 is null or blank"); } else { System.out.println("myString4 is not null and not blank"); } } }Save the file, compile, and run again:
javac NullCheck.java java NullCheckThe output for
myString4should now be:Checking myString4 with isBlank(): myString4 is null or blank
This demonstrates how to combine checks for null and empty/blank strings, which is a very common pattern in Java programming.
Use Optional to Handle Null Strings Safely
In the previous steps, we used the equality operator (==) and the isEmpty() or isBlank() methods to check for null and empty/blank strings. While these methods are effective, Java 8 introduced the Optional class as a way to handle potentially null values in a more explicit and functional way. Using Optional can help make your code more readable and less prone to NullPointerExceptions.
Optional is a container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value. If no value is present, the object is considered empty and isPresent() will return false. Calling get() on an empty Optional will throw a NoSuchElementException.
Let's explore how to use Optional with strings.
Open the
NullCheck.javafile in the WebIDE editor.Replace the entire contents of the file with the following code that uses
Optional:import java.util.Optional; public class NullCheck { public static void main(String[] args) { String myString1 = "Hello"; String myString2 = null; String myString3 = ""; String myString4 = " "; // Creating Optional objects from strings Optional<String> optionalString1 = Optional.ofNullable(myString1); Optional<String> optionalString2 = Optional.ofNullable(myString2); Optional<String> optionalString3 = Optional.ofNullable(myString3); Optional<String> optionalString4 = Optional.ofNullable(myString4); System.out.println("Checking optionalString1:"); if (optionalString1.isPresent()) { System.out.println("optionalString1 has a value: " + optionalString1.get()); } else { System.out.println("optionalString1 is empty (contains null)"); } System.out.println("\nChecking optionalString2:"); if (optionalString2.isPresent()) { System.out.println("optionalString2 has a value: " + optionalString2.get()); } else { System.out.println("optionalString2 is empty (contains null)"); } System.out.println("\nChecking optionalString3:"); // Optional.ofNullable("") creates an Optional containing an empty string if (optionalString3.isPresent()) { System.out.println("optionalString3 has a value: " + optionalString3.get()); } else { System.out.println("optionalString3 is empty (contains null)"); } System.out.println("\nChecking optionalString4:"); if (optionalString4.isPresent()) { System.out.println("optionalString4 has a value: " + optionalString4.get()); } else { System.out.println("optionalString4 is empty (contains null)"); } // Using Optional methods for safer handling System.out.println("\nUsing Optional methods:"); // orElse: provides a default value if the Optional is empty String value1 = optionalString1.orElse("Default Value"); String value2 = optionalString2.orElse("Default Value"); System.out.println("Value from optionalString1 (orElse): " + value1); System.out.println("Value from optionalString2 (orElse): " + value2); // ifPresent: performs an action if a value is present System.out.print("If optionalString1 is present: "); optionalString1.ifPresent(s -> System.out.println("Value is " + s)); System.out.print("If optionalString2 is present: "); optionalString2.ifPresent(s -> System.out.println("Value is " + s)); // filter: filters the value if present System.out.print("Filtered optionalString1 (length > 3): "); optionalString1.filter(s -> s.length() > 3).ifPresent(s -> System.out.println("Value is " + s)); System.out.print("Filtered optionalString3 (length > 3): "); optionalString3.filter(s -> s.length() > 3).ifPresent(s -> System.out.println("Value is " + s)); } }In this code:
- We import the
Optionalclass. - We use
Optional.ofNullable(string)to create anOptional<String>from a regularString. This method is safe to use even if the input string isnull. If the input isnull, it returns an emptyOptional; otherwise, it returns anOptionalcontaining the string. - We use
optionalString.isPresent()to check if theOptionalcontains a value. - We use
optionalString.get()to retrieve the value if it is present. Be careful: callingget()on an emptyOptionalwill throw an exception, so always checkisPresent()first or use other safer methods. - We demonstrate
orElse(defaultValue)which returns the contained value if present, otherwise returns the specified default value. - We demonstrate
ifPresent(consumer)which executes the given consumer (a function that takes one argument and returns no result) if a value is present. - We demonstrate
filter(predicate)which returns anOptionalcontaining the value if it is present and matches the given predicate (a function that returns a boolean), otherwise returns an emptyOptional.
- We import the
Save the
NullCheck.javafile.Compile the program in the Terminal:
javac NullCheck.javaRun the program:
java NullCheckYou should see output similar to this:
Checking optionalString1: optionalString1 has a value: Hello Checking optionalString2: optionalString2 is empty (contains null) Checking optionalString3: optionalString3 has a value: Checking optionalString4: optionalString4 has a value: Using Optional methods: Value from optionalString1 (orElse): Hello Value from optionalString2 (orElse): Default Value If optionalString1 is present: Value is Hello If optionalString2 is present: Filtered optionalString1 (length > 3): Value is Hello Filtered optionalString3 (length > 3):
Using Optional can make your code more expressive about whether a value might be absent and provides useful methods for handling the presence or absence of a value without explicit null checks everywhere. While Optional is a powerful tool, it's not a replacement for all null checks, but it's particularly useful when dealing with return values that might be null.
Summary
In this lab, we learned how to check if a string in Java is null. We started by using the equality operator (==) to directly compare a string variable with null, understanding that null signifies the absence of an object reference and that failing to check for null can lead to NullPointerException.
We then explored how to combine the null check with a check for an empty string, recognizing that an empty string ("") is a valid object, unlike null. Finally, we learned how to use the Optional class, introduced in Java 8, as a more modern and safer way to handle potentially null values, promoting more robust and readable code by explicitly indicating the possibility of a missing value.



