Java Stack - The Coding Shala

Home >> Learn Java >> Java Stack

Java Stack

In this post, we will discuss What is a Java Stack class and how to implement it in Java?

Java Stack class is a part of the Java Collections framework. The stack is Data Structure also known as Last-in-first-out(LIFO) data structure. In Stack, the newest element added to the stack will be processed first. Like Queue in stack two operations are important. One is inserting operation is called a push. A new element is always added at the end of the stack. The delete operation is called pop, will always remove the last element.

Java Stack Implementation

The Following Java program explains the stack Implementation: 

import java.util.Stack;

class Main{
 public static void main(String[] args) {
  //initialize stack
  Stack<Integer> stack = new Stack<Integer>();
  
  //add element into stack
  //we use push() method
  stack.push(1);
  stack.push(2);
  stack.push(3);
  stack.push(5);
  System.out.println("Stack is: "+ stack);
  
  //check top element
  //use peek() method
  System.out.println("Top element is: "+ stack.peek());
  
  //remove element from top
  //use pop() method
  stack.pop();
  System.out.println("Stack is: "+stack);
  
  //size of stack
  //size() method
  System.out.println("Size of Stack is: "+stack.size());
  
  //check empty or not
  //use empty() method
  System.out.println("Stack is empty? "+ stack.empty());
  stack.pop();
  stack.pop();
  stack.pop();
  System.out.println("Stack is empty? "+ stack.empty());
 }
}
Output: 

Stack is: [1, 2, 3, 5]
Top element is: 5
Stack is: [1, 2, 3]
Size of Stack is: 3
Stack is empty? false
Stack is empty? true


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala