The java.util.Stack.empty() method is used to check whether a stack contains any elements. It returns a boolean value—true if the stack is empty, and false otherwise. This method is commonly used to avoid EmptyStackException, control stack traversal, and implement safe error handling.
Syntax:
stack.empty()
- Parameters: The method does not take any parameters.Â
- Return Value: The method returns true if the stack is empty, else it returns false.Â
Example 1: Checking Stack Emptiness Before and After Pop
import java.util.Stack;
public class StackDemo {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("Geeks");
stack.push("4");
stack.push("Geeks");
stack.push("Welcomes");
stack.push("You");
System.out.println("Stack: " + stack);
System.out.println("Is stack empty? " + stack.empty());
while (!stack.empty()) {
stack.pop();
}
System.out.println("Is stack empty? " + stack.empty());
}
}
Output
Stack: [Geeks, 4, Geeks, Welcomes, You] Is stack empty? false Is stack empty? true
Example 2: Checking Emptiness of an Integer Stack
import java.util.Stack;
public class StackDemo {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(8);
stack.push(5);
stack.push(9);
stack.push(2);
stack.push(4);
System.out.println("Stack: " + stack);
System.out.println("Is stack empty? " + stack.empty());
}
}
Output
Stack: [8, 5, 9, 2, 4] Is stack empty? false
Example 3: Traversing a Stack Using empty() (Sum of Elements)
import java.util.Stack;
public class StackDemo {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(23);
stack.push(3);
stack.push(-30);
stack.push(13);
stack.push(45);
System.out.println("Stack: " + stack);
int sum = 0;
while (!stack.empty()) {
sum += stack.pop();
}
System.out.println("Sum of elements: " + sum);
System.out.println("Is stack empty? " + stack.empty());
}
}
Output
Stack: [23, 3, -30, 13, 45] Sum of elements: 54 Is stack empty? true
Example 4: Using empty() for Error Handling
The empty() method is useful for validating input scenarios, such as checking whether a file contains data before processing.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Stack;
public class FileReadExample {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
try {
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
stack.push(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
if (stack.empty()) {
System.out.println("File is empty.");
} else {
System.out.println("File is not empty. Stack contents:");
while (!stack.empty()) {
System.out.println(stack.pop());
}
}
}
}
Output
File not found. File is empty.