Write a Java program to search an item in a Stack collection


The code demonstrates how to search for an item in a stack in Java using the search method of the Stack class. Let's go through the code step by step:

  • The code begins by importing the necessary libraries: java.io.* and java.util.*.
  • The Search_Item class is defined, serving as the entry point of the program.
  • In the main method, a new stack object named stck_list is created using the raw Stack class, without specifying the type of elements it will contain. As mentioned before, it is recommended to use generics to provide type safety.
  • Several strings, namely "Red," "Pink," "Yellow," "Blue," "Green," and "Orange," are pushed onto the stack using the push method.
  • The System.out.println statement is used to print the contents of the stack. The string representation of the stack is obtained by concatenating the stack with the string "Stack Elements : " using the + operator.
  • The search method is then used to find the position of the string "Blue" within the stack. The result is stored in the ind variable.
  • Finally, another System.out.println statement is used to display the position of "Blue" within the stack by concatenating the string "Position of 'Blue' is : " with the value of ind.

Source Code

import java.io.*;
import java.util.*;
public class Search_Item
{
	public static void main(String[] args)
	{
		Stack stck_list = new Stack();
		int ind = 0;
 
		stck_list.push("Red");
		stck_list.push("Pink");
		stck_list.push("Yellow");
		stck_list.push("Blue");
		stck_list.push("Green");
		stck_list.push("Orange");
		System.out.println("Stack Elements : " + stck_list);;
 
		ind = stck_list.search("Blue");
		System.out.println("Position of 'Blue' is : " + ind);
	}
}

Output

Stack Elements : [Red, Pink, Yellow, Blue, Green, Orange]
Position of 'Blue' is : 3