Stack contains() method in Java with Example

The java.util.Stack.contains() method is used to check whether a specific element is present in the Stack or not. So basically it is used to check if a Stack contains any particular element or not.

Syntax:

Stack.contains(Object element)

Parameters: This method takes a mandatory parameter element which is of the type of Stack. This is the element that needs to be tested if it is present in the Stack or not.

Return Value: This method returns True if the element is present in the Stack otherwise it returns False.

Below programs illustrate the Java.util.Stack.contains() method:

Program 1:




// Java code to illustrate contains()
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack<String> stack = new Stack<String>();
  
        // Use add() method to add elements into the Stack
        stack.add("Welcome");
        stack.add("To");
        stack.add("Beginner");
        stack.add("4");
        stack.add("Beginner");
  
        // Displaying the Stack
        System.out.println("Stack: " + stack);
  
        // Check for "Beginner" in the Stack
        System.out.println("Does the Stack contains 'Beginner'? "
                           + stack.contains("Beginner"));
  
        // Check for "4" in the Stack
        System.out.println("Does the Stack contains '4'? "
                           + stack.contains("4"));
  
        // Check if the Queue contains "No"
        System.out.println("Does the Stack contains 'No'? "
                           + stack.contains("No"));
    }
}


Output:

Stack: [Welcome, To, Beginner, 4, Beginner]
Does the Stack contains 'Beginner'? true
Does the Stack contains '4'? true
Does the Stack contains 'No'? false

Program 2:




// Java code to illustrate contains()
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack<Integer> stack = new Stack<Integer>();
  
        // Use add() method to add elements into the Stack
        stack.add(10);
        stack.add(15);
        stack.add(30);
        stack.add(20);
        stack.add(5);
  
        // Displaying the Stack
        System.out.println("Stack: " + stack);
  
        // Check for "Beginner" in the Stack
        System.out.println("Does the Stack contains 'Beginner'? "
                           + stack.contains("Beginner"));
  
        // Check for "4" in the Stack
        System.out.println("Does the Stack contains '4'? "
                           + stack.contains("4"));
  
        // Check if the Stack contains "No"
        System.out.println("Does the Stack contains 'No'? "
                           + stack.contains("No"));
    }
}


Output:

Stack: [10, 15, 30, 20, 5]
Does the Stack contains 'Beginner'? false
Does the Stack contains '4'? false
Does the Stack contains 'No'? false


Contact Us