Create Stack in Java - How to add Elements to Stack

Published April 04, 2022

The first step in creating a stack in Java is to import the Java.util.stack package. After importing the package, follow the syntax below to create a stack in Java:

Stack<Type> stacks = new Stack<>();

 

The Stack Methods

  • push() method: This method adds an element to the top of the stack.

  • pop() method: removes an element from the top of the stack.

  • peek()method:  this method returns an object from the top of the stack.

  • search() method: this method is used to search for an element in the stack.

  • empty() method: this method checks whether a stack is empty or not.

 

Simple Stack Example

In the Example below, we are going to create a  stack named "vehicles"and then add elements to it using the push() method

 

import java.util.Stack;

public class StackExample {

    public static void main(String[] args) {

        Stack<String> vehicles= new Stack<>();

            // Add the Stack elements

            vehicles.push("mazda");

            vehicles.push("Rover");

            vehicles.push("Benz");

            System.out.println("Stack: " + vehicles);

    }

}

 

 

Output:

Stack :[mazda,Rover, Benz]

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

208 Views