String Existence in Varargs in Java


Create a Java program demonstrating a method with varargs that checks if a given string exists in a list of strings (case-insensitive)

  • The class StringChecker contains a single static method checkString that takes two parameters: search, which is the string to search for, and strings, which is a variable number of strings (using varargs).
  • Inside the checkString method, it iterates over each string in the strings array.
  • For each string, it checks if it is equal to the search string using the equals method. If a match is found, it returns true.
  • If no match is found after iterating through all the strings, it returns false.
  • In the main method, the checkString method is called with the search string "Pink" and a list of strings to demonstrate its functionality. The result is printed to the console.

Source Code

public class StringChecker
{
	static boolean checkString(String search, String... strings)
	{
		for (String str : strings)
		{
			if (str.equals(search))
			{
				return true;
			}
		}
		return false;
	}
 
	public static void main(String[] args)
	{
		boolean exists = checkString("Pink", "Blue", "White", "Pink", "Black");
		System.out.println("String Exists : " + exists);
	}
}

Output

String Exists : true

Example Programs