Stack is a collection class in Java that is used to implement a data structure called the stack. A stack is a Last-In-First-Out (LIFO) data structure, which means that the last element added to the stack is the first one to be removed. The Stack class in Java provides methods to add, remove, and access elements in the stack.
The Stack class has only one constructor:
1. Stack(): This constructor creates an empty stack.
Here are some of the methods of the Stack class in Java:
1. push(E item): This method is used to add an element to the top of the stack.
2. pop(): This method is used to remove and return the top element from the stack.
3. peek(): This method is used to return the top element from the stack without removing it.
4. empty(): This method is used to check if the stack is empty.
5. search(Object o): This method is used to search for the specified element in the stack and return its position.
Here's an example that demonstrates how to use Stack and its methods in Java:
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
// Creating a Stack
Stack<Integer> stack = new Stack<>();
// Adding elements to the Stack using push() method
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
// Printing the Stack
System.out.println("Original Stack: " + stack);
// Removing the top element from the Stack using pop() method
int element = stack.pop();
System.out.println("Element removed from Stack: " + element);
// Printing the updated Stack
System.out.println("Stack after removing top element: " + stack);
// Retrieving the top element from the Stack using peek() method
int topElement = stack.peek();
System.out.println("Top element of Stack: " + topElement);
// Checking if the Stack is empty using empty() method
boolean isEmpty = stack.empty();
System.out.println("Is Stack empty?: " + isEmpty);
// Searching for an element in the Stack using search() method
int position = stack.search(30);
System.out.println("Position of element '30' in Stack: " + position);
}
}
Output:
Original Stack: [10, 20, 30, 40, 50]
Element removed from Stack: 50
Stack after removing top element: [10, 20, 30, 40]
Top element of Stack: 40
Is Stack empty?: false
Position of element '30' in Stack: 2
In this example, we created a Stack and added elements to it using the push() method. We also demonstrated how to remove the top element from the Stack using pop() method, retrieve the top element from the Stack using peek() method, check if the Stack is empty using empty() method, and search for an element in the Stack using search() method.
Overall, the Stack class provides a simple and efficient way to implement the stack data structure in Java.