Introduction
In this lab, you will learn how to check if a string is empty in Java. We will explore three key techniques: using the length() method to verify string length, utilizing the dedicated isEmpty() method for a direct check, and importantly, handling potential null strings before performing emptiness checks to avoid errors. By the end of this lab, you will have a solid understanding of how to effectively determine the emptiness of strings in your Java programs.
Verify String Length Using length() Method
In this step, we will explore how to determine the length of a string in Java using the built-in length() method. Understanding string length is a fundamental concept when working with text data in any programming language.
In Java, a String is a sequence of characters. The length() method is a simple way to find out how many characters are in a string. It's like counting the letters in a word or the words in a sentence.
Let's create a simple Java program to demonstrate this.
Open the
HelloJava.javafile in the WebIDE editor if it's not already open.Replace the entire contents of the file with the following code:
public class HelloJava { public static void main(String[] args) { String greeting = "Hello, Java!"; int length = greeting.length(); System.out.println("The string is: " + greeting); System.out.println("The length of the string is: " + length); } }Let's look at the new parts of this code:
String greeting = "Hello, Java!";: This line declares a variable namedgreetingand assigns it the string value "Hello, Java!".int length = greeting.length();: This is where we use thelength()method. We calllength()on thegreetingstring, and it returns the number of characters in that string. This number is then stored in an integer variable namedlength.System.out.println("The string is: " + greeting);: This line prints the original string to the console.System.out.println("The length of the string is: " + length);: This line prints the calculated length of the string.
Save the file (Ctrl+S or Cmd+S).
Now, let's compile our program. Open the Terminal at the bottom of the WebIDE and make sure you are in the
~/projectdirectory. Then, run the following command:javac HelloJava.javaIf the compilation is successful, you will not see any output.
Finally, let's run the compiled program:
java HelloJavaYou should see output similar to this:
The string is: Hello, Java! The length of the string is: 12The output shows the original string and its length, which is 12 (including the comma, space, and exclamation mark).
You have successfully used the length() method to find the length of a string in Java! This is a basic but important operation when working with text data.
Check for Empty String with isEmpty() Method
In this step, we will learn how to check if a string is empty in Java using the isEmpty() method. An empty string is a string that has zero characters. It's different from a string that contains spaces or other characters.
The isEmpty() method is a convenient way to check if a string has a length of zero. It returns true if the string is empty and false otherwise.
Let's modify our HelloJava.java program to demonstrate the isEmpty() method.
Open the
HelloJava.javafile in the WebIDE editor.Replace the existing code with the following:
public class HelloJava { public static void main(String[] args) { String str1 = "Hello"; String str2 = ""; // This is an empty string String str3 = " "; // This string contains a space System.out.println("String 1: \"" + str1 + "\""); System.out.println("Is String 1 empty? " + str1.isEmpty()); System.out.println("\nString 2: \"" + str2 + "\""); System.out.println("Is String 2 empty? " + str2.isEmpty()); System.out.println("\nString 3: \"" + str3 + "\""); System.out.println("Is String 3 empty? " + str3.isEmpty()); } }In this code:
- We declare three strings:
str1with content,str2which is empty, andstr3which contains a space. - We use
str1.isEmpty(),str2.isEmpty(), andstr3.isEmpty()to check if each string is empty. - The
System.out.println()statements will print the string and the result of theisEmpty()check (trueorfalse).
- We declare three strings:
Save the file (Ctrl+S or Cmd+S).
Compile the modified program in the Terminal:
javac HelloJava.javaAgain, no output means successful compilation.
Run the program:
java HelloJavaYou should see output similar to this:
String 1: "Hello" Is String 1 empty? false String 2: "" Is String 2 empty? true String 3: " " Is String 3 empty? falseAs you can see,
isEmpty()correctly identifiesstr2as empty (true) but notstr1orstr3(false). This is becausestr3contains a space character, even though it looks like it might be empty.
You have successfully used the isEmpty() method to check if strings are empty. This is useful for validating user input or processing text data where you need to handle cases of missing or empty strings.
Handle Null Strings Before Checking Emptiness
In the previous step, we learned how to use the isEmpty() method to check if a string is empty. However, there's an important concept in Java called null. A null value means that a variable does not refer to any object. If you try to call a method like isEmpty() on a null string, your program will crash with a NullPointerException.
It's crucial to handle null strings before attempting to call any methods on them. The safest way to do this is to check if the string is null first.
Let's modify our program to demonstrate how to handle null strings.
Open the
HelloJava.javafile in the WebIDE editor.Replace the existing code with the following:
public class HelloJava { public static void main(String[] args) { String str1 = "Hello"; String str2 = ""; String str3 = null; // This string is null System.out.println("Checking String 1: \"" + str1 + "\""); if (str1 != null && !str1.isEmpty()) { System.out.println("String 1 is not null and not empty."); } else { System.out.println("String 1 is null or empty."); } System.out.println("\nChecking String 2: \"" + str2 + "\""); if (str2 != null && !str2.isEmpty()) { System.out.println("String 2 is not null and not empty."); } else { System.out.println("String 2 is null or empty."); } System.out.println("\nChecking String 3: " + str3); // Note: printing null doesn't crash if (str3 != null && !str3.isEmpty()) { System.out.println("String 3 is not null and not empty."); } else { System.out.println("String 3 is null or empty."); } } }In this code:
- We introduce a
nullstringstr3. - Before calling
isEmpty(), we first check if the string isnullusingstr != null. - We use the logical AND operator (
&&) to combine thenullcheck and theisEmpty()check. The!str.isEmpty()part is only evaluated ifstr != nullis true, preventing theNullPointerException. - The
ifstatement checks if the string is not null AND not empty.
- We introduce a
Save the file (Ctrl+S or Cmd+S).
Compile the program in the Terminal:
javac HelloJava.javaRun the program:
java HelloJavaYou should see output similar to this:
Checking String 1: "Hello" String 1 is not null and not empty. Checking String 2: "" String 2 is null or empty. Checking String 3: null String 3 is null or empty.This output shows that our code correctly identifies
str1as not null and not empty, andstr2andstr3as null or empty, without crashing.
By checking for null before calling methods on strings, you make your Java programs more robust and prevent common errors. This is a very important practice in Java programming.
Summary
In this lab, we learned how to check if a string is empty in Java. We started by exploring the length() method to determine the number of characters in a string, which is a fundamental concept for working with text data. We wrote a simple Java program to demonstrate how to use length() and print the string and its length to the console.
We will continue to explore other methods like isEmpty() and learn how to handle null strings to ensure robust emptiness checks in our Java programs.



