Java Stack contains() Method

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

Definition

In Java, contains(o) returns true if at least one element of a Stack equals o, wherever it sits, and false otherwise. The stack is not changed.

It checks with equals(), scanning from the bottom, and is equivalent to indexOf(o) >= 0. Use it when you only need a yes or no; search() also tells you how deep the element is.

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 look for.

Java
Stack<String> stack = new Stack<>();
stack.push("home");
stack.push("about");
boolean a = stack.contains("about");   // true
boolean b = stack.contains("blog");    // false
boolean c = stack.contains(null);      // false (no null pushed)
CallWhat it does
stack.contains(o)true if any element equals o.
!stack.contains(o)A guard before pushing, to avoid duplicates.
stack.search(o) != -1The same answer from Stack's own method.
stack.indexOf(o) >= 0How contains is implemented.

contains is a linear scan. For frequent membership checks on a large stack, keep a HashSet alongside it.

Library declarations
Java
// java.util.Vector<E>, inherited by Stack<E>
public boolean contains(Object o)

// body: return indexOf(o, 0) >= 0;

Parameters

ParameterDescription
o (Object)The value to look for; null is allowed.

Return Value

Return ValueDescription
booleantrue if some element equals o, otherwise false.

Compare with Similar Methods

Other membership and lookup methods:

MethodHow it differs
search(o)Also tells you the distance from the top.
indexOf(o)Returns the position from the bottom.
removeElement(o)Finds the first match and removes it.
ArrayList.contains()The same check on a list.

Java Examples

Example 1 — Has This Page Been Visited?

Check three page names against a stack of visited pages.

Java
import java.util.Stack;

public class StackContainsDemo {
    public static void main(String[] args) {
        Stack<String> visited = new Stack<>();
        visited.push("home");
        visited.push("pricing");
        visited.push("signup");

        String[] pages = {"pricing", "blog", "home"};
        for (String p : pages) {
            System.out.println(p + " visited? " + visited.contains(p));
        }
        System.out.println("stack unchanged: " + visited);
    }
}

How It Works

  1. Any depth counts. pricing is in the middle and home at the bottom, yet contains finds both; position does not matter.
  2. Missing value. blog was never pushed, so the scan reaches the end and returns false.
  3. A read-only check. Unlike pop, contains leaves all three pages where they were.

Example 2 — Recent Searches Without Duplicates

Keep each search term once, with the most recent one on top.

Java
import java.util.Stack;

public class StackContainsNoDuplicates {
    public static void main(String[] args) {
        Stack<String> recent = new Stack<>();
        String[] typed = {"java", "stack", "java", "queue", "stack"};

        for (String q : typed) {
            if (recent.contains(q)) {
                recent.remove(q);
            }
            recent.push(q);
        }
        System.out.println("recent: " + recent);
        System.out.println("latest: " + recent.peek());
    }
}

How It Works

  1. Check before pushing. For each query, contains tells whether it is already somewhere in the stack.
  2. Move repeats to the top. A repeated query is removed from its old position with remove(Object) and pushed again, so java and stack each appear once.
  3. Most recent on top. stack was typed last, so it is the top that peek() returns, and the stack holds three unique queries.

Example 3 — Integer vs String, and null

Search a stack of numeric IDs with the right type, the wrong type, and null.

Java
import java.util.Stack;

public class StackContainsTypes {
    public static void main(String[] args) {
        Stack<Integer> ids = new Stack<>();
        ids.push(101);
        ids.push(202);

        System.out.println("contains(202):    " + ids.contains(202));
        System.out.println("contains(\"202\"):  " + ids.contains("202"));
        System.out.println("contains(null):   " + ids.contains(null));
        ids.push(null);
        System.out.println("after push(null): " + ids.contains(null));
    }
}

How It Works

  1. Autoboxing makes 202 an Integer. contains(202) boxes the int, and Integer.equals compares values, so the result is true.
  2. Wrong type, silent false. The String "202" is never equal to an Integer; the call compiles because the parameter is Object, but it can never match.
  3. null works both ways. contains(null) is false until a null element is pushed, then true, and no NullPointerException is thrown.

Frequently Asked Questions

It returns true if any element of the stack equals the argument, no matter how deep it is.
equals(). Two different String objects with the same text match. A null argument matches a null element.
contains() returns only true or false. search() returns the 1-based distance from the top, or -1 when the element is missing.
"5" is a String and the elements are Integer objects, which are never equal to a String. Pass the number 5 instead.
It checks elements one by one, so it slows down as the stack grows. Keep a HashSet next to the stack if you check membership very often.

Next: elementAt()

Vector's legacy name for reading by index.

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

15 people found this page helpful