Write a Java program to Check whether a HashSet contains a specified item or not


The program starts with the import statement import java.util.*;, which imports all classes from the java.util package, including HashSet.

  • The program defines a public class called Check_Item. Within the Check_Item class, the main method is declared and serves as the entry point for the program. It takes an array of strings (args) as input.
  • Inside the main method, a new instance of the HashSet class is created using the constructor: HashSet<String> fr = new HashSet<String>();. The specifies the type of elements that will be stored in the HashSet, which in this case is a string.
  • After that, several elements are added to the fr HashSet using the add() method. The elements added are "Mulberry", "Banana", "Mango", "Watermelon", "Guava", and "Pineapple".
  • The program then checks if the HashSet fr contains the element "Watermelon" using the contains() method. If the HashSet contains "Watermelon", it prints "Watermelon Found in the HashSet." Otherwise, it prints "Watermelon Not Found in the HashSet."
  • Next, the program checks if the HashSet fr contains the element "Apple" using the contains() method. If the HashSet contains "Apple", it prints "Apple Found in the HashSet." Otherwise, it prints "Apple Not Found in the HashSet."

Source Code

import java.util.*;
public class Check_Item
{
	public static void main(String[] args)
	{
		HashSet<String> fr = new HashSet<String>();
		fr.add("Mulberry");
		fr.add("Banana");
		fr.add("Mango");
		fr.add("Watermelon");
		fr.add("Guava");
		fr.add("Pineapple ");
 
		if (fr.contains("Watermelon"))
		{			
			System.out.println("Watermelon Found in the HashSet.");
		}
		else
		{			
			System.out.println("Watermelon Not Found in the HashSet.");
		}
		if (fr.contains("Apple"))
		{
			System.out.println("Apple Found in the HashSet.");	
		}
		else
		{
			System.out.println("Apple Not Found in the HashSet.");
		}
	}
}

Output

Watermelon Found in the HashSet.
Apple Not Found in the HashSet.

Example Programs