Count Long Strings with Varargs in Java


Create a Java program demonstrating a method with varargs that finds the count of strings longer than a given length

It contains a method named countLongStrings, which takes an integer length and a variable number of strings as input. This method counts the number of strings in the input array that have a length greater than the specified length. It iterates through each string in the array and checks if its length is greater than the specified length. If so, it increments the count.

The main method serves as the entry point of the program. Inside main, it calls the countLongStrings method with the length 5 and several strings as arguments. It stores the result in the variable longStringsCount.

Finally, it prints out the result using System.out.println, displaying "Count of Strings Longer than 5 Characters : " followed by the calculated count of strings longer than 5 characters.

Source Code

public class LongStringCounter
{
	static int countLongStrings(int length, String... strings)
	{
		int count = 0;
		for (String str : strings)
		{
			if (str.length() > length)
			{
				count++;
			}
		}
		return count;
	}
 
	public static void main(String[] args)
	{
		int longStringsCount = countLongStrings(5, "Java", "Python", "JavaScript", "C++", "Ruby");
		System.out.println("Count of Strings Longer than 5 Characters : " + longStringsCount);
	}
}

Output

Count of Strings Longer than 5 Characters : 2

Example Programs