Master java skills

Stack in Java

Stack is also a linear data structure that maintains LIFO (Last In First Out) order. So, the element that goes first in the stack, comes out last.

A real world example would be a stack of books. If you arrage books on top of each other, normally, you would take out the book that is on the top i.e. the book that was added last to the stack.

It is just opposite to the queue. Queue maintains FIFO order, whereas, stack maintains LIFO order.

Push and Pop Operations in Stack

Push means inserting a new element into a stack. Pop means popping out (removing) top element from a stack.

Class Declaration

public class Stack extends Vector

As we can see, Stack class extends Vector class. Stack also is an index based collection.

Top value of stack

Top value of a stack represents the index of top most element. So, if there are 10 elements in the stack, the value of top would be 9. A value -1 represents that the stack is empty. Below are various values of top of stack

Top valueExplanation
-1The stack is empty
0The stack has one element
N-1The stack is full
NThe stack is overflowed

Methods summary of Stack class

MethodDescription
empty()checks whether the stack is empty or not
push(E item)pushes one element into the stack
pop()pops (removes) top element from the stack and returns the same
peek()retrieves the top element in the stack, but doesn’t remove it.
search(Object o)searches the specified object in the stack.

Stack Example

package com.javatrainingschool;

import java.util.Stack;

public class StackExample {

	public static void main(String[] args) {
		
		Stack<Integer> stack = new Stack<Integer>();
		stack.push(100);
		stack.push(101);
		stack.push(102);
		stack.push(103);
		stack.push(104);
		
		System.out.println("Size of the stack = " + stack.size());
		
		System.out.println(stack.pop());
		
		System.out.println("Size of the stack = " + stack.size());
		
		System.out.println(stack.peek());
		
		System.out.println("Size of the stack = " + stack.size());
		
		System.out.println("Index of 102 = " + stack.search(102));
		
		for(int element : stack) {
			System.out.println("Element = " + element);
		}
	}
}
Output :

Size of the stack = 5
104
Size of the stack = 4
103
Size of the stack = 4
Index of 102 = 2
Element = 100
Element = 101
Element = 102
Element = 103