Java Utility Library

Java Stack - push() Method



The java.util.Stack.push() method adds a new element at the top of the stack and returns the argument element as the value of this method. In a stack, addition and deletion of a element occurs from the top of the stack. Hence, the most recently added element will be the top element of the stack. Addition of new element always occurs after its most recently added element and every addition results into increasing the stack size by one.

This method has same effect as addElement method.

Syntax

public E push (E element)

Here, E is the type of element maintained by the container.


Parameters

element Specify the element which need to be added in the stack.

Return Value

Returns the argument element.

Exception

NA

Example:

In the example below, the java.util.Stack.push() method is used to add a new element at the top of the stack called MyStack.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a stack
    Stack<Integer> MyStack = new Stack<Integer>();

    //pushulating stack
    System.out.println(MyStack.push(10) + " is added in MyStack.");
    System.out.println(MyStack.push(20) + " is added in MyStack.");
    System.out.println(MyStack.push(30) + " is added in MyStack.");

    //printing stack
    System.out.println("MyStack contains: " + MyStack);
  }
}

The output of the above code will be:

10 is added in MyStack.
20 is added in MyStack.
30 is added in MyStack.
MyStack contains: [10, 20, 30]

❮ Java.util - Stack