Java stack
Created By: chatGPT
In Java, a Stack is a data structure that follows the Last In First Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed. The stack is part of the Java Collections Framework and is implemented as the
Stack
class. Let's dive into how to use the Stack
class effectively.import java.util.Stack;
To utilize a stack, you first need to create an instance of the
Stack
class. You can define it to hold specific types of data using generics.Stack<String> stack = new Stack<>();
You can add elements to the stack using the
push
method. This method adds an element to the top of the stack.stack.push("First");
stack.push("Second");
stack.push("Third");
To remove the top element from the stack, you use the
pop
method. This method not only removes the top element but also returns it, so you can capture its value.String topElement = stack.pop();
System.out.println("Popped Element: " + topElement);
You can look at the top element without removing it by using the
peek
method. This gives you a view of the top element while keeping it in the stack.String peekedElement = stack.peek();
System.out.println("Top Element: " + peekedElement);
To check if the stack is empty, you can use the
isEmpty
method. This is useful to avoid popping from an empty stack, which would throw an EmptyStackException.if (stack.isEmpty()) {
System.out.println("The stack is empty!");
} else {
System.out.println("The stack is not empty.");
}
You can also retrieve the size of the stack by using the
size
method, which returns the number of elements in the stack.int size = stack.size();
System.out.println("Size of Stack: " + size);
Here’s a complete example that demonstrates creating a stack, adding elements, and performing various operations:
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("First");
stack.push("Second");
stack.push("Third");
System.out.println("Top Element: " + stack.peek());
System.out.println("Popped Element: " + stack.pop());
System.out.println("Size: " + stack.size());
if (stack.isEmpty()) {
System.out.println("Stack is empty!");
} else {
System.out.println("Stack is not empty.");
}
}
}