Find Index with Varargs in Java


Create a Java program to demonstrate a method with varargs that finds the index of a given string in a list of strings

  • The class StringIndexFinder contains a single static method findStringIndex that takes two parameters: a search string and a variable number of strings.
  • Inside the method, it iterates over each string in the strings array using a loop.
  • For each string, it checks if it equals the search string using the equals method.
  • If a match is found, it returns the index of the string in the array.
  • If no match is found after iterating through all strings, it returns -1 to indicate that the search string was not found.
  • In the main method, the findStringIndex method is called to search for the string "Pink" in the provided array of strings. If the string is found, its index is printed to the console. Otherwise, a message indicating that the string was not found is printed.

Source Code

public class StringIndexFinder
{
	static int findStringIndex(String search, String... strings)
	{
		for (int i = 0; i < strings.length; i++)
		{
			if (strings[i].equals(search))
			{
				return i;
			}
		}
		return -1;
	}
 
	public static void main(String[] args)
	{
		int index = findStringIndex("Pink", "Blue", "Pink", "White", "Black");
		if (index != -1)
		{
			System.out.println("String Found at index : " + index);
		}
		else
		{
			System.out.println("String Not Found");
		}
	}
}

Output

String Found at index : 1

Example Programs