Java/J2EE and SOA (348 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (345 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

What is Stack Class in Java and how to use it?

Last updated on Nov 26,2019 7.6K Views

Aayushi Johari
A technophile with a passion for unraveling the intricate tapestry of the... A technophile with a passion for unraveling the intricate tapestry of the tech world. I've spent over a decade exploring the fascinating world of...
72 / 72 Blog from Java Core Concepts

Data Structures have been a boon to the programming world as they simplify programming to a great extent. Stack class in Java is a part of Collection framework that simplifies various operations like push, pop, etc. In this article we explore this concept in detail. Following pointers will be explored in this article:

Let’s get started.

What is a Stack Class in Java?

A stack is a data structure which follows LIFO (Last In First Out). Java Stack Class falls under the basic Collection Hierarchy Framework in which you can perform the basic operations such as push, pop, etc. We know that Java collection framework includes interfaces and classes. Now, let’s have a clear view of how stack class in Java is arranged in the Java collections framework hierarchy.

Hierarchy - Stack Class in Java - Edureka

In the above hierarchy, the blue box refers to the different interfaces and the yellow box defines the class. A stack in Java extends the vector class which further implements List interface. Whenever you create a Stack, initially it does not contain any item, i.e, the Stack is empty.

Moving ahead, let’s see the different methods of Java Stack Class.

Methods of Stack Class in Java

In Java, there are mainly 5 methods of Stack Class. Following are the methods that are at our disposal when we use the stack class in Java.

MethodsDescription

empty()

Checks if the stack is empty

push()

Pust an item to the top of the stack

pop()

Remove the object from the stack

peek()

Looks at the object of a stack without removing it

search()

Searches item in the stack to get its index

Let us understand each of these methods with a programmatic example:

package Edureka;

import java.io.*; 
import java.util.*; 

public class StackMethods
	{    
	//add or push element on the top of the stack 
	   static void push_method(Stack st, int n) {
	      st.push(new Integer(n));
	      System.out.println("push(" +n+ ")");
	      System.out.println("Current Stack: " + st);
	   }
    // Display element on the top of the stack 
	   static void peek_method(Stack<Integer> st) 
		  { 
			  Integer element = (Integer) st.peek(); 
			  System.out.println("Element on stack top : " + element); 
		  }
	// Searches element in the stack
	   static void search_method(Stack st, int element) 
	    { 
	        Integer pos = (Integer) st.search(element); 
	  
	        if(pos == -1) 
	            System.out.println("Element not found"); 
	        else
	            System.out.println("Element is found at position " + pos); 
	    } 
	// Removes element from the top of the stack
	   static void pop_method(Stack st) {
		      System.out.print("pop = ");
		      Integer n = (Integer) st.pop();
		      System.out.println(n);
		      System.out.println("Remaining stack: " + st);
		   }
	   public static void main(String args[]) {
	      Stack st = new Stack();
	      System.out.println("Empty stack: " + st);
	      push_method(st, 4);
	      push_method(st, 8);
	      push_method(st, 9);
	      peek_method(st);
	      search_method(st, 2); 
	      search_method(st, 4);
	      pop_method(st);
	      pop_method(st);
	      pop_method(st);
	      try {
	         pop_method(st);
	      } catch (EmptyStackException e) {
	         System.out.println("empty stack");
	      }
	   }
} 

Output:

Empty stack: []
push(4)
Current Stack: [4]
push(8)
Current Stack: [4, 8]
push(9)
Current Stack: [4, 8, 9]
Element on stack top: 9
Element not found
Element is found at position 3
pop = 9
Remaining stack: [4, 8]
pop = 8
Remaining stack: [4]
pop = 4
Remaining stack: []
pop = empty stack

Explanation: In the above Java program, I have first printed an empty stack and added a few elements using the Push method. Once the elements are present in the stack, I have displayed the elements on the top of the stack using the Peek method. After that, I have performed searching using the Search method and finally removed the elements in the Java Stack class using the Pop method.

Moving ahead with Java Stack Class, let’s have a look at various operations you can perform while implementing stack class in Java.

Java Stack Operations:

Size of the stack:

package Edureka;

import java.util.EmptyStackException;
import java.util.Stack;

public class StackOperations {  
public static void main (String[] args) 
{ 
	Stack stack = new Stack();
	stack.push("1");
	stack.push("2");
	stack.push("3");
	// Check if the Stack is empty
	        System.out.println("Is the Java Stack empty? " + stack.isEmpty());

	// Find the size of Stack
	        System.out.println("Size of Stack : " + stack.size());
	}
} 

Output: Is the Java Stack empty? false
Size of Stack : 3

Iterate Elements of a Java Stack:

  • Iterate over a Stack using iterator()
  • Iterate over a Stack using Java 8 forEach()
  • Iterate over a Stack using listIterator() from Top to Bottom

Let’s begin to iterate elements by using iterator().

package Edureka;
import java.util.EmptyStackException;
import java.util.Iterator;
import java.util.Stack;
public class StackOperations {
public static void main (String[] args) 
{ 
	Stack stack = new Stack();
	stack.push("1");
	stack.push("2");
	stack.push("3");
	Iterator iterator = stack.iterator();
	while(iterator.hasNext()){
	      Object value = iterator.next();
	      System.out.println(value); 
	        }	
}
} 

Output:

1
2
3

Similarly, you can perform the iteration by other methods. Refer the below code for more understanding:

package demo;

import java.util.EmptyStackException;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Stack;

public class JavaOperators {
		     

public static void main (String[] args) 
{ 
	Stack stack = new Stack();

	stack.push("1");
	stack.push("2");
	stack.push("3");
	
    System.out.println("Iterate a stack using forEach() Method:");
    stack.forEach(n ->; {
        System.out.println(n);
    });
    
    ListIterator<String> ListIterator = stack.listIterator(stack.size());
    System.out.println("Iterate over a Stack using listIterator() from Top to Bottom:");
    while (ListIterator.hasPrevious()) {
    	String str = ListIterator.previous();
        System.out.println(str);
}
}}

Output: Iterate a stack using forEach() Method:
1
2
3
Iterate over a Stack using listIterator() from Top to Bottom:
3
2
1

Explanation: In the above code, you can see the iteration using forEach() Method and then reverse the same using listIterator() from top to bottom of the stack.

This is the end of the “Stack Class in Java” blog. I hope you guys are clear with Java collections framework, it’s hierarchy along with the Java Stack class example codes. Do read my next blog on Java Interview Questions where I have listed top 75 interview questions and answers which will help you set apart in the interview process.

Now that you have understood Java Collections, check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Stack class in Java” blog and we will get back to you as soon as possible.

Upcoming Batches For Java Certification Training Course
Course NameDateDetails
Java Certification Training Course

Class Starts on 27th April,2024

27th April

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

What is Stack Class in Java and how to use it?

edureka.co