String Existence Case-Sensitive with Varargs in Java


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

  • The StringChecker class contains a static method named checkString that takes two parameters: a search string (search) and a variable number of strings (strings).
  • Inside the method, it iterates through each string in the strings array using an enhanced for loop.
  • For each string, it checks if it equals the search string using the equals method.
  • If a string equals the search string, it returns true, indicating that the string exists in the array.
  • If no match is found after iterating through all strings, it returns false.
  • In the main method, the checkString method is called with the search string "Pink" and a list of strings ("Blue", "White", "pink", "Black").
  • The result is printed to the console, indicating whether the search string exists in the provided list of strings. In this case, it prints String Exists : true because "Pink" (case-sensitive) is found in the list.

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 : false

Example Programs