1. Introduction
The LinkedList class in Java provides a handy method named isEmpty() which returns true if the list is empty, and false otherwise. This method is very useful when you need to check whether a list has elements before performing operations on it.
2. Program Steps
1. Create a LinkedList.
2. Check and print whether the LinkedList is empty using the isEmpty() method.
3. Add some elements to the LinkedList.
4. Again, check and print whether the LinkedList is empty.
3. Code Program
import java.util.LinkedList;
public class LinkedListIsEmptyExample {
public static void main(String[] args) {
// Step 1: Create a LinkedList
LinkedList<String> fruits = new LinkedList<>();
// Step 2: Check and print whether the LinkedList is empty
System.out.println("Is the LinkedList empty? " + fruits.isEmpty());
// Step 3: Add some elements to the LinkedList
fruits.add("Apple");
fruits.add("Banana");
// Step 4: Again, check and print whether the LinkedList is empty
System.out.println("Is the LinkedList empty? " + fruits.isEmpty());
}
}
Output:
Is the LinkedList empty? true Is the LinkedList empty? false
4. Step By Step Explanation
Step 1: A LinkedList named fruits is created, and initially, it has no elements.
Step 2: The isEmpty() method is called on the fruits LinkedList to check if it's empty, and the result (true) is printed to the console.
Step 3: Two elements, "Apple" and "Banana", are added to the fruits LinkedList.
Step 4: The isEmpty() method is again called on the updated fruits LinkedList to check if it's still empty, and the result (false) is printed to the console.