The Stack class in Java is a collection class that is used to implement the stack data structure. A stack is a data structure that follows the LIFO (Last In First Out) principle, where the last element added to the stack is the first element to be removed from the stack. In this article, we will discuss the Stack class in Java in detail.
What is Stack Class in Java?
The Stack class in Java is a part of the java.util package, and it is used to implement the stack data structure. The Stack class extends the Vector class and provides a set of methods that can be used to manipulate the elements in the stack.
Stack Syntax:
The syntax for creating a Stack in Java is as follows:
Stack stackName = new Stack();
In this syntax, “DataType” refers to the data type of the elements that will be stored in the Stack, and “stackName” is the name of the Stack.
Stack Methods:
The Stack class provides a set of methods that can be used to manipulate the elements in the stack. Here are some of the most commonly used methods:
- push(element): This method is used to add an element to the top of the stack.
- pop(): This method is used to remove the element at the top of the stack and return it.
- peek(): This method is used to retrieve the element at the top of the stack without removing it.
- empty(): This method is used to check whether the stack is empty or not.
- search(element): This method is used to search for an element in the stack and return its position.
Example of Stack in Java:
Here is an example of how to use a Stack in Java:
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack stack = new Stack();
stack.push("apple");
stack.push("banana");
stack.push("orange");
System.out.println(stack.pop());
System.out.println(stack.peek());
System.out.println(stack.empty());
System.out.println(stack.search("banana"));
}
}
In this example, we first import the Stack class from the java.util package. We then create a new Stack called “stack” that can hold strings. We add three elements to the Stack, with “orange” being the element at the top of the stack. We then remove the element at the top of the stack, which is “orange”, and print it out. We then print out the element at the top of the stack, which is “banana”, without removing it. We then check whether the stack is empty or not, which is false. Finally, we search for the element “banana” in the stack and print out its position, which is 2.
Conclusion:
In conclusion, the Stack class in Java is a useful data structure that is used to implement the stack data structure. It provides a set of methods that can be used to manipulate the elements in the stack. The Stack class is useful in various scenarios, such as in algorithms that require LIFO behavior, like reversing a string or evaluating postfix expressions.