OneBite.Dev - Coding blog in a bite size

count the number of occurrences of a specific element in an array in java

Code snippet on how to count the number of occurrences of a specific element in an array in java

  int count = 0;
  int[] array = {1, 5, 9, 3, 5, 1, 9, 3};
  int targetNum = 5;
  
  for (int i = 0; i < array.length; i++) {
      if (array[i] == targetNum) {
          count++;
      }
  }
  System.out.println("Number of occurrences of element " + targetNum + " is " + count);

This code snippet iterates through an array, and uses a counter variable to track the number of occurrences of a specified element in the array. Firstly, a counter variable is initialized. Then we create an array, and define a target number to be searched for in the array. The for loop iterates through each element in the array, and if the element is equivalent to the target number, then the counter is incremented. After the loop is finished, the result is printed to the console.

java