Count Integer Occurrences with Varargs in Java


Write a Java program demonstrating a method with varargs that counts the occurrences of a specific integer in a sequence of integers

  • The IntCounter class contains a static method countOccurrences that takes two parameters: search, which is the integer value to search for, and numbers, which is a variable number of integers.
  • Inside the method, an int variable count is initialized to track the occurrences of the search value.
  • The method iterates through each integer in the numbers array using an enhanced for loop.
  • If the current number (num) matches the search value, the counter (count) is incremented.
  • Finally, the total count of occurrences is returned.
  • In the main method, the countOccurrences method is called with the search value 3 and a list of integers. The result is then printed to the console.

Source Code

public class IntCounter
{
	static int countOccurrences(int search, int... numbers)
	{
		int count = 0;
		for (int num : numbers)
		{
			if (num == search)
			{
				count++;
			}
		}
		return count;
	}
 
	public static void main(String[] args)
	{
		int occurrences = countOccurrences(3, 1, 3, 5, 2, 7, 3, 9);
		System.out.println("Occurrences of 3 : " + occurrences);
	}
}

Output

Occurrences of 3 : 2

Example Programs