Introduction
In this lab, you will learn how to check if a Set in Java is empty. We will explore the standard isEmpty() method, a simple and efficient way to determine if a set contains any elements.
You will also learn how to verify the size of a set using the size() method and understand how to handle potential NullPointerException when dealing with null sets. By the end of this lab, you will be proficient in checking the emptiness of Java sets under various scenarios.
Use isEmpty() for Set Check
In this step, we will learn how to check if a Set in Java is empty using the isEmpty() method. A Set is a collection that cannot contain duplicate elements. The isEmpty() method is a simple and efficient way to determine if a collection contains any elements.
First, let's create a new Java file named
SetCheck.javain your~/projectdirectory. You can do this by right-clicking in the File Explorer on the left and selecting "New File", then typingSetCheck.java.Open the
SetCheck.javafile in the editor and add the following code:import java.util.HashSet; import java.util.Set; public class SetCheck { public static void main(String[] args) { // Create a new HashSet Set<String> fruits = new HashSet<>(); // Check if the set is empty using isEmpty() boolean isEmptyBeforeAdd = fruits.isEmpty(); System.out.println("Is the fruits set empty before adding elements? " + isEmptyBeforeAdd); // Add some elements to the set fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); // Check if the set is empty after adding elements boolean isEmptyAfterAdd = fruits.isEmpty(); System.out.println("Is the fruits set empty after adding elements? " + isEmptyAfterAdd); } }Let's break down the new parts of this code:
import java.util.HashSet;andimport java.util.Set;: These lines import the necessary classes to work withSetandHashSet.Set<String> fruits = new HashSet<>();: This line creates a newHashSetobject namedfruits. We specify<String>to indicate that this set will storeStringobjects.boolean isEmptyBeforeAdd = fruits.isEmpty();: This line calls theisEmpty()method on thefruitsset and stores the result (eithertrueorfalse) in a boolean variable namedisEmptyBeforeAdd.fruits.add("Apple");: This line adds the string "Apple" to thefruitsset.boolean isEmptyAfterAdd = fruits.isEmpty();: This line checks if the set is empty again after adding elements.
Save the
SetCheck.javafile (Ctrl+S or Cmd+S).Now, let's compile the Java program. Open the Terminal at the bottom of the WebIDE and make sure you are in the
~/projectdirectory. Then, run the following command:javac SetCheck.javaIf the compilation is successful, you will not see any output.
Finally, run the compiled program using the
javacommand:java SetCheckYou should see output similar to this:
Is the fruits set empty before adding elements? true Is the fruits set empty after adding elements? falseThis output confirms that the
isEmpty()method correctly reported the state of the set before and after adding elements.
Verify Set Size with size()
In the previous step, we learned how to check if a Set is empty using isEmpty(). Another common operation is to find out how many elements are in a Set. For this, we use the size() method. The size() method returns the number of elements currently in the set.
Open the
SetCheck.javafile in your~/projectdirectory in the WebIDE editor.Modify the
mainmethod to include calls to thesize()method. Replace the existingmainmethod with the following code:import java.util.HashSet; import java.util.Set; public class SetCheck { public static void main(String[] args) { // Create a new HashSet Set<String> fruits = new HashSet<>(); // Check the size of the set before adding elements int sizeBeforeAdd = fruits.size(); System.out.println("Size of the fruits set before adding elements: " + sizeBeforeAdd); // Add some elements to the set fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); // Check the size of the set after adding elements int sizeAfterAdd = fruits.size(); System.out.println("Size of the fruits set after adding elements: " + sizeAfterAdd); // Add a duplicate element (Sets do not allow duplicates) fruits.add("Apple"); // Check the size again int sizeAfterDuplicateAdd = fruits.size(); System.out.println("Size of the fruits set after adding a duplicate: " + sizeAfterDuplicateAdd); } }Here's what we added:
int sizeBeforeAdd = fruits.size();: This line calls thesize()method on thefruitsset and stores the returned integer value (the number of elements) in a variable namedsizeBeforeAdd.int sizeAfterAdd = fruits.size();: This checks the size after adding the initial three elements.fruits.add("Apple");: We attempt to add "Apple" again. Since "Apple" is already in the set, this operation will not change the set's contents.int sizeAfterDuplicateAdd = fruits.size();: This checks the size after attempting to add a duplicate.
Save the
SetCheck.javafile.Compile the modified Java program in the Terminal:
javac SetCheck.javaAgain, no output indicates successful compilation.
Run the program:
java SetCheckYou should see output similar to this:
Size of the fruits set before adding elements: 0 Size of the fruits set after adding elements: 3 Size of the fruits set after adding a duplicate: 3This output shows that the
size()method correctly reports the number of elements, and that adding a duplicate element does not increase the size of the set.
Handle Null Sets
In the previous steps, we worked with a Set that was properly initialized. However, in real-world programming, you might encounter situations where a Set variable is null. Attempting to call methods like isEmpty() or size() on a null object will result in a NullPointerException, which is a common error in Java. It's important to handle these cases gracefully.
Open the
SetCheck.javafile in your~/projectdirectory in the WebIDE editor.Modify the
mainmethod to demonstrate how to handle anullset. Replace the existingmainmethod with the following code:import java.util.HashSet; import java.util.Set; public class SetCheck { public static void main(String[] args) { // Declare a Set variable but initialize it to null Set<String> colors = null; // Attempting to call isEmpty() or size() here would cause a NullPointerException // System.out.println("Is the colors set empty? " + colors.isEmpty()); // This would crash! // To safely check if a set is null or empty, we first check for null if (colors == null) { System.out.println("The colors set is null."); } else { // If it's not null, we can safely check if it's empty if (colors.isEmpty()) { System.out.println("The colors set is empty."); } else { System.out.println("The colors set is not empty and has " + colors.size() + " elements."); } } // Now, let's initialize the set and add elements colors = new HashSet<>(); colors.add("Red"); colors.add("Blue"); // Check again after initialization and adding elements if (colors == null) { System.out.println("The colors set is null."); } else { if (colors.isEmpty()) { System.out.println("The colors set is empty."); } else { System.out.println("The colors set is not empty and has " + colors.size() + " elements."); } } } }In this updated code:
Set<String> colors = null;: We declare aSetvariablecolorsbut explicitly set it tonull.- We commented out the line that would cause a
NullPointerException. if (colors == null): This is the crucial check. Before calling any methods on thecolorsvariable, we first check if it isnull.- If
colorsis notnull, we then proceed to check if it's empty usingcolors.isEmpty()or get its size usingcolors.size(). - We then initialize
colorswith a newHashSetand add elements to show the different output when the set is not null and not empty.
Save the
SetCheck.javafile.Compile the program in the Terminal:
javac SetCheck.javaRun the program:
java SetCheckYou should see output similar to this:
The colors set is null. The colors set is not empty and has 2 elements.This demonstrates how to safely handle potential
nullvalues for aSetvariable before attempting to access its methods. Always check fornullfirst when dealing with object references that might not be initialized.
Summary
In this lab, we learned how to check if a Set in Java is empty. We started by using the isEmpty() method, which is the standard and most efficient way to perform this check. We created a HashSet, checked its empty status before and after adding elements, and observed the boolean output of isEmpty(). This demonstrated the basic usage of isEmpty() for determining if a set contains any elements.



