- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to find if an element is in Stack
The method java.util.Stack.search() is used to find if an element is in the stack or not in Java. This method takes a single parameter i.e. the element that is searched in the stack. It returns the position of the element in the stack(counting from one) if it is available and returns -1 if the element is not available in the stack.
A program that demonstrates this is given as follows −
Example
import java.util.Stack; public class Demo { public static void main (String args[]) { Stack stack = new Stack(); stack.push("Apple"); stack.push("Mango"); stack.push("Pear"); stack.push("Orange"); stack.push("Guava"); System.out.println("The stack elements are: " + stack); System.out.println("The element Mango is in the stack at position: " + stack.search("Mango")); System.out.println("The element Peach is in the stack at position: " + stack.search("Peach")); } }
Output
The stack elements are: [Apple, Mango, Pear, Orange, Guava] The element Mango is in the stack at position: 4 The element Peach is in the stack at position: -1
Now let us understand the above program.
The Stack is created. Then Stack.push() method is used to add the elements to the stack. The stack is displayed and then the Stack.search() method is used to find if the elements “Mango” and “Peach” are in the stack or not. A code snippet which demonstrates this is as follows −
Stack stack = new Stack(); stack.push("Apple"); stack.push("Mango"); stack.push("Pear"); stack.push("Orange"); stack.push("Guava"); System.out.println("The stack elements are: " + stack); System.out.println("The element Mango is in the stack at position: " + stack.search("Mango")); System.out.println("The element Peach is in the stack at position: " + stack.search("Peach"));
Advertisements