Count Character Occurrences with Varargs in Java


Create a Java program to demonstrate a method with varargs that counts the occurrence of characters in a string

  • The CharacterCounter class contains a static method named countCharacters that counts the occurrences of a specific character within an array of characters.
  • It takes two arguments: the character to search for (search) and an array of characters (characters).
  • Inside the method, it initializes a variable count to 0 to store the count of occurrences.
  • It iterates through each character c in the array of characters.
  • For each character, if it matches the search character, it increments the count variable.
  • After iterating through all characters, it returns the total count of occurrences.
  • In the main method, the countCharacters method is called with the search character 'a' and a sequence of characters 'a', 'b', 'c', 'a', 'd', 'a'.
  • The output will be the count of occurrences of the character 'a', which is printed to the console.

Source Code

public class CharacterCounter
{
	static int countCharacters(char search, char... characters)
	{
		int count = 0;
		for (char c : characters)
		{
			if (c == search)
			{
				count++;
			}
		}
		return count;
	}
 
	public static void main(String[] args)
	{
		int occurrence = countCharacters('a', 'a', 'b', 'c', 'a', 'd', 'a');
		System.out.println("Occurrences of 'a' : " + occurrence);
	}
}

Output

Occurrences of 'a' : 3

Example Programs