Java Stack indexOf() Method

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

Definition

In Java, indexOf(o) finds the first element equal to o and returns its index, counting from the bottom of the stack at 0. If nothing matches, it returns -1.

Because it scans upward from the bottom, it finds the oldest copy of a repeated element. Vector adds an overload indexOf(o, fromIndex) that starts the scan at a given index, useful when you need every position. Stack's own search() measures from the top instead.

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.

Syntax

Pass the value to find, and optionally the index where the upward scan starts.

Java
Stack<String> stack = new Stack<>();
stack.push("red");
stack.push("green");
stack.push("blue");
stack.push("green");                  // [red, green, blue, green]
int a = stack.indexOf("green");       // 1  (first match from the bottom)
int b = stack.indexOf("green", 2);    // 3  (scan starts at index 2)
int c = stack.indexOf("pink");        // -1
CallWhat it does
stack.indexOf(o)Index of the first match from the bottom, or -1.
stack.indexOf(o, from)The same scan starting at index from.
stack.indexOf(o) >= 0The same test as contains(o).
stack.search(o)A 1-based distance from the top instead.

indexOf checks elements one by one, so its running time grows with the size of the stack.

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

Parameters

ParameterDescription
o (Object)The value to find, compared with equals(); null finds a null element.
index (int)Only in the two-argument form: where the upward scan starts.

Return Value

Return ValueDescription
intThe 0-based index of the first match at or above the start index, or -1.

Compare with Similar Methods

Other ways to locate an element:

MethodHow it differs
lastIndexOf(o)Finds the match closest to the top.
search(o)Distance from the top, starting at 1.
contains(o)Only says whether there is a match.
ArrayList.indexOf()The same one-argument method on a list.

Java Examples

Example 1 — Find a Command in Shell History

A shell keeps typed commands in a stack; find where each command first appears.

Java
import java.util.Stack;

public class StackIndexOfDemo {
    public static void main(String[] args) {
        Stack<String> commands = new Stack<>();
        commands.push("cd src");
        commands.push("ls");
        commands.push("javac Main.java");
        commands.push("ls");

        System.out.println("history: " + commands);
        System.out.println("indexOf(ls): " + commands.indexOf("ls"));
        System.out.println("indexOf(javac Main.java): " + commands.indexOf("javac Main.java"));
        System.out.println("indexOf(rm): " + commands.indexOf("rm"));
    }
}

How It Works

  1. Scan from the bottom. ls was typed twice; indexOf starts at index 0 and stops at the first ls, index 1.
  2. Exact text match. "javac Main.java" equals the stored string at index 2, so that index is returned.
  3. No match is -1. rm was never typed, so the result is -1, a value that can never be a real index.

Example 2 — Find Every Six with indexOf(o, from)

A stack of dice rolls (fixed values): list every index that holds a 6.

Java
import java.util.Stack;

public class StackIndexOfAll {
    public static void main(String[] args) {
        Stack<Integer> rolls = new Stack<>();
        int[] values = {6, 2, 6, 4, 6};
        for (int v : values) {
            rolls.push(v);
        }

        StringBuilder positions = new StringBuilder();
        int i = rolls.indexOf(6);
        while (i != -1) {
            positions.append(i).append(' ');
            i = rolls.indexOf(6, i + 1);
        }
        System.out.println("rolls: " + rolls);
        System.out.println("sixes at: " + positions.toString().trim());
    }
}

How It Works

  1. Start with the first match. indexOf(6) finds the bottom-most 6 at index 0.
  2. Resume just after it. indexOf(6, i + 1) continues the upward scan from the next index, finding 2 and then 4.
  3. Stop on -1. When the scan starts at 5, past the top, no 6 is left, the loop ends, and trim() removes the trailing space.

Example 3 — What Counts as a Match?

A Stack<Object> holds a String, an Integer, a null, and a String built with new.

Java
import java.util.Stack;

public class StackIndexOfEquals {
    public static void main(String[] args) {
        Stack<Object> mixed = new Stack<>();
        mixed.push("7");
        mixed.push(7);
        mixed.push(null);
        mixed.push(new String("seven"));

        System.out.println("indexOf(7):       " + mixed.indexOf(7));
        System.out.println("indexOf(\"7\"):     " + mixed.indexOf("7"));
        System.out.println("indexOf(null):    " + mixed.indexOf(null));
        System.out.println("indexOf(seven):   " + mixed.indexOf("seven"));
    }
}

How It Works

  1. Type matters. The Integer 7 and the String "7" are not equal, so indexOf(7) finds index 1 and indexOf("7") finds index 0.
  2. null can be found. indexOf(null) compares with == for this special case and returns 2.
  3. equals, not identity. The element at index 3 was created with new String, yet the literal "seven" matches it because String.equals compares characters.

Frequently Asked Questions

The 0-based index of the first element equal to the argument, counted from the bottom, or -1 if there is none.
From the bottom. Index 0 is the first element pushed. Use search() for a distance from the top.
With equals(), so two different String objects with the same text match. A null argument matches a null element.
Call indexOf(o) and then repeatedly indexOf(o, previous + 1) until it returns -1.
indexOf() returns the match closest to the bottom; lastIndexOf() returns the match closest to the top.

Next: insertElementAt()

Insert below the top: arguments are (element, index).

insertElementAt() 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