Java Stack search() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Stack method

Definition

In Java, search(o) tells you how far an element is from the top of a Stack. The top element is at distance 1, the one below it at 2, and so on. If the element is not on the stack, the result is -1.

Put differently, search answers "how many pops until this element comes off?". It compares with equals(), and when the element appears more than once it reports the copy closest to the top. The stack itself is not changed.

Declared in java.util.Stack itself (since Java 1.0). Stack<E> extends Vector<E> and keeps the top at the end of the vector, so printing a stack lists it from bottom to top.

1-based from the top, not 0-based from the bottom.

search counts from the top starting at 1, while the inherited indexOf() and get() count from the bottom starting at 0. For an element that appears once, search(o) equals size() - indexOf(o).

Syntax

Pass the element to look for; the result is a distance, not an index.

Java
Stack<String> stack = new Stack<>();
stack.push("a");
stack.push("b");
stack.push("c");                 // [a, b, c]  c is the top
int top = stack.search("c");     // 1
int bottom = stack.search("a");  // 3
int none = stack.search("z");    // -1
CallWhat it does
stack.search(o)Distance of o from the top (top = 1), or -1.
stack.search(o) > 0The same test as contains(o).
stack.size() - stack.lastIndexOf(o)How search computes its result when o is present.
stack.indexOf(o)0-based position from the bottom (first match).

search scans from the top down, so the deeper the element, the longer it takes: a linear-time operation on a large stack.

Library declarations
Java
// java.util.Stack<E>
public synchronized int search(Object o)

// body: int i = lastIndexOf(o); return i >= 0 ? size() - i : -1;

Parameters

ParameterDescription
o (Object)The element to look for, compared with equals(). null is allowed and finds a null element.

Return Value

Return ValueDescription
int1 for the top element, 2 for the one below it, and so on; -1 if no element equals o.

Compare with Similar Methods

Other ways to locate an element:

MethodHow it differs
indexOf(o)0-based from the bottom; finds the copy nearest the bottom.
lastIndexOf(o)0-based from the bottom; finds the copy nearest the top (search is built on it).
contains(o)Answers only true or false.
peek()Reads the element at distance 1 directly.

Java Examples

Example 1 — How Far Down Is Each Tray?

A cafeteria tray stack: measure each color's distance from the top.

Java
import java.util.Stack;

public class StackSearchDistance {
    public static void main(String[] args) {
        Stack<String> trays = new Stack<>();
        trays.push("blue");
        trays.push("green");
        trays.push("red");
        trays.push("yellow");

        System.out.println("trays: " + trays);
        System.out.println("yellow: " + trays.search("yellow"));
        System.out.println("green:  " + trays.search("green"));
        System.out.println("blue:   " + trays.search("blue"));
        System.out.println("purple: " + trays.search("purple"));
    }
}

How It Works

  1. The top is 1. yellow was pushed last, so search("yellow") returns 1, not 0.
  2. Count downward. green is the third tray from the top, and blue, at the bottom, is the fourth, matching the stack size.
  3. Missing means -1. No tray equals purple, so search returns -1 and the stack stays untouched.

Example 2 — search() vs indexOf() with a Repeated Call

A call history where load was called twice shows which copy each method finds.

Java
import java.util.Stack;

public class StackSearchDuplicates {
    public static void main(String[] args) {
        Stack<String> calls = new Stack<>();
        calls.push("main");
        calls.push("load");
        calls.push("parse");
        calls.push("load");

        System.out.println("calls: " + calls);
        System.out.println("search(load):      " + calls.search("load"));
        System.out.println("indexOf(load):     " + calls.indexOf("load"));
        System.out.println("lastIndexOf(load): " + calls.lastIndexOf("load"));
        System.out.println("search(main):      " + calls.search("main"));
    }
}

How It Works

  1. Two copies of load. The method was called twice, so "load" sits at index 1 and again at index 3, on top.
  2. search sees the top copy. It uses lastIndexOf, finds index 3, and converts it to a distance: 4 - 3 = 1.
  3. Same number, different meaning. indexOf also prints 1, but that is index 1 from the bottom, the older copy of load; main, at the bottom, is 4 from the top.

Example 3 — Dig Out a Box

Find the passport box, then lift exactly as many boxes as search says.

Java
import java.util.Stack;

public class StackSearchDig {
    public static void main(String[] args) {
        Stack<String> boxes = new Stack<>();
        boxes.push("winter clothes");
        boxes.push("passport");
        boxes.push("books");
        boxes.push("toys");

        int depth = boxes.search("passport");
        System.out.println("passport is " + depth + " boxes down");
        for (int i = 0; i < depth; i++) {
            System.out.println("lift: " + boxes.pop());
        }
        System.out.println("left: " + boxes);
    }
}

How It Works

  1. Ask before digging. passport is at index 1 in a stack of 4, so search returns 4 - 1 = 3.
  2. Distance equals pops. Popping exactly 3 times lifts toys and books, and the third pop returns the passport box itself.
  3. Only the boxes below stay. The winter clothes were under the passport, so that box is all that is left.

Frequently Asked Questions

The 1-based distance of the element from the top: 1 for the top element, 2 for the next, and so on. It returns -1 if the element is not on the stack.
It is defined as a distance from the top, so the top element is 1. The number tells you how many pops it takes to remove that element.
The distance of the copy closest to the top, because search is computed from lastIndexOf().
search() counts from the top starting at 1. indexOf() counts from the bottom starting at 0 and finds the copy closest to the bottom.
No. It only reports a position; the stack is not changed.

Next: add()

Append at the top (returns true) or insert at an index.

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