Java Stack set() Method

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

Definition

In Java, set(index, element) replaces the element at a position in a Stack and returns the element that was there before. The size does not change.

Index 0 is the bottom and size() - 1 is the top, so stack.set(stack.size() - 1, x) swaps out the top element without a pop and a push. The legacy setElementAt() does the same job but returns nothing.

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

Syntax

Pass the index first, then the new element; keep the returned old value if you need it.

Java
Stack<String> stack = new Stack<>();
stack.push("hte");
stack.push("cat");                   // [hte, cat]
String old = stack.set(0, "the");    // old is "hte", stack is [the, cat]
stack.set(stack.size() - 1, "dog");  // replaces the top: [the, dog]
stack.set(2, "x");                   // throws ArrayIndexOutOfBoundsException
CallWhat it does
stack.set(i, e)Replaces the element at i; returns the old one.
stack.set(stack.size() - 1, e)Replaces the top in one step.
stack.set(0, e)Replaces the bottom.
stack.setElementAt(e, i)The legacy equivalent: arguments reversed, no return value.

set is a constant-time array write; nothing shifts.

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

Parameters

ParameterDescription
index (int)Position to replace, from 0 (bottom) to size() - 1 (top).
element (E)The new value; null is allowed.

Return Value

Return ValueDescription
EThe previous element at that index (it can be null).

Compare with Similar Methods

Related ways to change one position:

MethodHow it differs
setElementAt(e, i)The same replacement in (element, index) order; returns nothing.
get(i)Reads the element without replacing it.
add(i, e)Inserts a new element instead of replacing.
ArrayList.set()The same method on an unsynchronized list.

Java Examples

Example 1 — Fix a Typo and Keep the Old Word

Correct the bottom word of a stack of typed words and report what was replaced.

Java
import java.util.Stack;

public class StackSetFixTypo {
    public static void main(String[] args) {
        Stack<String> words = new Stack<>();
        words.push("hte");
        words.push("cat");
        words.push("sat");

        String old = words.set(0, "the");
        System.out.println("replaced \"" + old + "\"");
        System.out.println("words: " + words);
        System.out.println("size still " + words.size());
    }
}

How It Works

  1. The first word typed is index 0. hte was pushed first, so it sits at the bottom and set(0, "the") targets it.
  2. The old value comes back. set returns "hte", which the program prints inside escaped quotes so the user sees what was corrected.
  3. Replace, not insert. The stack still holds three words; only the bottom one changed.

Example 2 — Change the Top Value Without Popping

A calculator multiplies the value on top of its stack by 10 in place, then bumps the bottom value.

Java
import java.util.Stack;

public class StackSetTop {
    public static void main(String[] args) {
        Stack<Integer> calc = new Stack<>();
        calc.push(4);
        calc.push(7);

        int old = calc.set(calc.size() - 1, calc.peek() * 10);
        System.out.println("top was " + old + ", now " + calc.peek());
        System.out.println("stack: " + calc);

        calc.set(0, calc.get(0) + 1);
        System.out.println("bottom bumped: " + calc);
    }
}

How It Works

  1. Address the top by index. calc.size() - 1 is 1, the index of the top value 7.
  2. One call instead of pop and push. set stores 70 there and returns 7, which is unboxed into the int variable old.
  3. Read, modify, write. set(0, get(0) + 1) increments the bottom value in place, turning 4 into 5.

Example 3 — set() Cannot Create a New Slot

Try to set a fourth slot on a three-element stack, then make room and try again.

Java
import java.util.Stack;

public class StackSetBounds {
    public static void main(String[] args) {
        Stack<String> slots = new Stack<>();
        slots.push("A");
        slots.push("B");
        slots.push("C");

        try {
            slots.set(3, "D");
        } catch (IndexOutOfBoundsException e) {
            System.out.println("set(3, D) failed: only indexes 0 to " + (slots.size() - 1));
        }
        slots.push("D");
        System.out.println("push works: " + slots);
        System.out.println("set(3, E) returns " + slots.set(3, "E") + ": " + slots);
    }
}

How It Works

  1. No slot 3 yet. With three elements the valid indexes are 0 to 2, so set(3, "D") throws; catching IndexOutOfBoundsException also covers the concrete ArrayIndexOutOfBoundsException.
  2. Grow first. push("D") creates index 3 at the top of the stack.
  3. Now set succeeds. set(3, "E") replaces D with E and returns D; the concatenation runs the call before it prints the stack.

Frequently Asked Questions

The element that was previously at that index. The new element takes its place and the size stays the same.
size() - 1. Index 0 is the bottom, the first element pushed.
No. It only replaces existing elements. An index equal to size() or larger throws an index exception; use push or add instead.
set(index, element) returns the old value and follows the List argument order. setElementAt(element, index) is the legacy Vector version with reversed arguments and no return value.
No. Only the value at one index changes; every other element stays where it was.

Next: setElementAt()

Replace by index with arguments (element, index); returns nothing.

setElementAt() 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.

10 people found this page helpful