Java Stack insertElementAt() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Inherited from Vector

Definition

In Java, insertElementAt(obj, index) is the legacy Vector method that inserts an element at a position in a Stack. Elements at that index and above move up by one, so the stack grows by one.

It does exactly what add(index, element) does; in fact add(index, element) calls it. The catch is the argument order: the element comes first and the index second. It returns nothing.

An instance method inherited from java.util.Vector (since Java 1.0). Stack does not override it: index 0 is the bottom of the stack and index size() - 1 is the top.

Watch the argument order.

insertElementAt(element, index) versus add(index, element). On a Stack<Integer> both arguments can be numbers, so swapping them still compiles and either inserts the wrong value or throws an exception.

Syntax

Pass the element first, then the index where it should go.

Java
Stack<String> stack = new Stack<>();
stack.push("base");
stack.push("top");                    // [base, top]
stack.insertElementAt("middle", 1);   // [base, middle, top]
stack.insertElementAt("floor", 0);    // [floor, base, middle, top]
stack.add(1, "same effect");          // add(index, element): reversed order
CallWhat it does
stack.insertElementAt(e, 0)Puts e at the bottom.
stack.insertElementAt(e, i)Puts e at index i; elements from i upward shift by one.
stack.insertElementAt(e, stack.size())Appends at the top, like push(e) without a return value.
stack.add(i, e)The List-style equivalent with the arguments reversed.

Inserting shifts every element above the index, so the cost grows with how far below the top you insert.

Library declarations
Java
// java.util.Vector<E>, inherited by Stack<E>
public synchronized void insertElementAt(E obj, int index)

Parameters

ParameterDescription
obj (E)The element to insert; null is allowed.
index (int)Where to insert, from 0 (bottom) to size() (new top).

Return Value

Return ValueDescription
voidNothing. Read the stack afterwards to see the result.

Compare with Similar Methods

Methods that insert or overwrite by index:

MethodHow it differs
add(index, e)The same insert in List argument order; also has add(e).
setElementAt(e, i)The same argument order, but it replaces instead of inserting.
push(e)Always inserts at the top.
removeElementAt(i)The opposite: removes at an index.

Java Examples

Example 1 — Add a Forgotten Layer to a Suitcase

A suitcase is packed bottom-up; the sweater was forgotten and belongs between the jeans and the shirts.

Java
import java.util.Stack;

public class StackInsertElementAtDemo {
    public static void main(String[] args) {
        Stack<String> suitcase = new Stack<>();
        suitcase.push("shoes");
        suitcase.push("jeans");
        suitcase.push("shirts");

        suitcase.insertElementAt("sweater", 2);
        System.out.println("layers: " + suitcase);
        System.out.println("sweater at index " + suitcase.indexOf("sweater"));
        System.out.println("still on top: " + suitcase.peek());
    }
}

How It Works

  1. Element first, index second. insertElementAt("sweater", 2) names the item and then the layer it should occupy.
  2. Upper layers move up. shirts was at index 2 and moves to 3; shoes and jeans below are not touched.
  3. Top unchanged. Because index 2 is below the top, peek() still returns shirts.

Example 2 — Swapped Arguments on an Integer Stack

With numbers as elements, the compiler cannot tell a value from an index. See a correct call, a silent mistake, and a loud one.

Java
import java.util.Stack;

public class StackInsertSwappedArgs {
    public static void main(String[] args) {
        Stack<Integer> nums = new Stack<>();
        nums.push(10);
        nums.push(20);
        nums.push(30);

        nums.add(1, 15);
        System.out.println("add(1, 15):             " + nums);
        nums.insertElementAt(25, 3);
        System.out.println("insertElementAt(25, 3): " + nums);
        nums.insertElementAt(0, 1);
        System.out.println("insertElementAt(0, 1):  " + nums);
        try {
            nums.insertElementAt(3, 40);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("insertElementAt(3, 40): index 40 is past size " + nums.size());
        }
    }
}

How It Works

  1. Two orders, same effect. add(1, 15) and insertElementAt(25, 3) both insert correctly, but the value comes second in one call and first in the other.
  2. A silent mix-up. Someone who meant "put 1 at the bottom" but wrote insertElementAt(0, 1) gets the value 0 at index 1; both arguments are numbers, so the compiler cannot help.
  3. A loud mix-up. insertElementAt(3, 40) treats 40 as the index; it is past the size 6, so ArrayIndexOutOfBoundsException is thrown and nothing is inserted.

Example 3 — Insert at the Very Bottom and the Very Top

Use index 0 and size() to reach both ends of a pile of mail.

Java
import java.util.Stack;

public class StackInsertAtEnds {
    public static void main(String[] args) {
        Stack<String> mail = new Stack<>();
        mail.push("magazine");
        mail.push("newspaper");

        mail.insertElementAt("old letter", 0);
        mail.insertElementAt("postcard", mail.size());
        System.out.println("mail:   " + mail);
        System.out.println("bottom: " + mail.firstElement());
        System.out.println("top:    " + mail.peek());
    }
}

How It Works

  1. Index 0 is the floor. The old letter is slipped under everything, so it becomes the bottom element that firstElement() returns.
  2. size() is the top slot. Inserting at mail.size() (3 at that moment) appends, the same position push would use.
  3. Both ends reached. The pile now holds four items, with the postcard on top, ready for the next pop().

Frequently Asked Questions

They do the same thing. insertElementAt takes (element, index) and is the old Vector name; add takes (index, element) and comes from the List interface.
insertElementAt throws ArrayIndexOutOfBoundsException. The valid range is 0 to size(), inclusive.
Yes. insertElementAt(e, stack.size()) appends e at the top, just like push(e), but it returns nothing.
No. It inserts and shifts the existing element up. Use setElementAt or set to replace.
Prefer add(index, element), which works on every List. Better still, keep stack code to push, pop, and peek.

Next: isEmpty()

The Collection-wide emptiness check.

isEmpty() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful