Professional Documents
Culture Documents
0 - Java Stack Class
0 - Java Stack Class
0 - Java Stack Class
In this tutorial, we will learn about the Java Stack class and its methods with the help of examples.
The Java collections framework has a class named Stack that provides the functionality of the stack data structure.
Stack Implementation
In stack, elements are stored and accessed in Last In First Out manner. That is, elements are added to the top of the stack and
removed from the top of the stack.
Creating a Stack
In order to create a stack, we must import the java.util.Stack package first. Once we import the package, here is how we can c
a stack in Java.
Here, Type indicates the stack's type. For example,
Stack Methods
Since Stack extends the Vector class, it inherits all the methods Vector . To learn about different Vector methods, visit Java V
Class.
Besides these methods, the Stack class includes 5 more methods that distinguish it from Vector .
push() Method
To add an element to the top of the stack, we use the push() method. For example,
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
Run Code
Output
pop() Method
To remove an element from the top of the stack, we use the pop() method. For example,
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
Run Code
Output
peek() Method
The peek() method returns an object from the top of the stack. For example,
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
}
}
Run Code
Output
search() Method
To search an element in the stack, we use the search() method. It returns the position of the element from the top of the stack.
example,
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
// Search an element
int position = animals.search("Horse");
System.out.println("Position of Horse: " + position);
}
}
Output
empty() Method
To check whether a stack is empty or not, we use the empty() method. For example,
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
Run Code
Output