Stack in Java : Complete Tutorial

What is a Stack ?

Stack is a linear data structure that follows the Last In First Out (LIFO) principle. In LIFO the last element added to the stack is the first element to be removed. In the world of computer programming stacks are often used to implement function calls, backtracking algorithms and etc,

For Example- Imagine a stack of plates, you add new plates on top, and when you need to remove one, you take it from the top. this example perfectly illustrates how a stack data structure works.

Stack in Java

Java provides a built-in Stack class available in java.util package, that implements the LIFO data structure. The Stack class is a subclass of the Vector class and provides all methods required for the stack.

Stack Constructors

  Stack s = new Stack();

Stack Methods

push()

public E push(     E item )

This method is used to insert an element into the stack.

pop()

public E pop()

This method removes and returns elements available at the top of the stack.

peek()

public E peek()

This method returns an element from the top of the stack without removing the element.

empty()

public boolean empty()

This method returns true if the stack is empty.

search()

public int search(     Object o )

This method returns the position of the element if the element is available in the stack otherwise it returns -1.

Stack Java Example

import java.util.Stack;

public class StackDemo {
    public static void main(String[] args) {
        Stack s = new Stack();
      s.push("The");
      s.push("Code");
      s.push("Data");
        System.out.println(s);
        System.out.println(s.search("Data"));
        System.out.println(s.pop());
        System.out.println(s);
        System.out.println(s.peek());
        System.out.println(s);
    }
}
Stack Java Example

Similar Java Tutorials

Leave a Comment