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
  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
  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());
  System.out.println("Stack is empty? "+ stack.empty());

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.


Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala