Count Uppercase Letters with Varargs in Java


Create a Java program to count the number of uppercase letters in a set of strings using varargs

  • The class imports the Arrays class from the java.util package to use its toString() method for printing arrays.
  • It contains a method called countUppercaseLetters, which takes a variable number of strings as input. Inside this method, it first prints out the given strings using Arrays.toString(strings) to display them. Then, it initializes a counter variable count to 0. It then iterates through each string in the input array and further iterates through each character in the string. For each character, it checks if it is an uppercase letter using Character.isUpperCase(c). If a character is uppercase, it increments the counter count.
  • The main method is the entry point of the program. Inside main, it calls the countUppercaseLetters method with several strings ("Blue", "PINK", "Black", "White") as arguments. It stores the result, which is the total count of uppercase letters, in the variable uppercaseCount.
  • Finally, the program prints out the result using System.out.println, displaying "Total Uppercase Letters : " followed by the calculated count of uppercase letters.

Source Code

import java.util.Arrays;
public class UppercaseLetterCounter
{
	static int countUppercaseLetters(String... strings)
	{
		System.out.println("Given String : " + Arrays.toString(strings));
		int count = 0;
		for (String str : strings)
		{
			for (char c : str.toCharArray())
			{
				if (Character.isUpperCase(c))
				{
					count++;
				}
			}
		}
		return count;
	}
 
	public static void main(String[] args)
	{
		int uppercaseCount = countUppercaseLetters("Blue", "PINK", "Black", "White");
		System.out.println("Total Uppercase Letters : " + uppercaseCount);
	}
}

Output

Given String : [Blue, PINK, Black, White]
Total Uppercase Letters : 7

Example Programs