Java Utility Library

Java Stack - add() Method



The java.util.Stack.add() method is used to insert the specified element at specified index in the stack. The method shifts the current element at the specified position (if any) and any subsequent elements to the up by adding one to their indices. Addition of new element results into increasing the stack size by one

Syntax

public void add(int index, E element)

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


Parameters

index Specify index number at which new element need to be inserted in the stack.
element Specify element which need to be inserted in the stack.

Return Value

void type.

Exception

Throws IndexOutOfBoundsException, if the index is out of range.

Example:

In the example below, the java.util.Stack.add() method is used to insert new element at specified position in the stack.

import java.util.*;

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

    //populating stack
    MyStack.push(10);
    MyStack.push(20);
    MyStack.push(30);

    //inserting new element in the stack
    MyStack.add(1,100);
    System.out.println("MyStack contains: " + MyStack); 

    //inserting new element in the stack
    MyStack.add(0,500);
    System.out.println("MyStack contains: " + MyStack);    
  }
}

The output of the above code will be:

MyStack contains: [10, 100, 20, 30]
MyStack contains: [500, 10, 100, 20, 30]

❮ Java.util - Stack