Java program that counts the number of occurrences of a specific character in a string

In the Java interview, one of the most commonly asked interview questions is to write a Java program to count the number of occurrences of a specific character in a String. If you prepare well in advance, you can quickly and confidently answer or write this Java program to qualify for the upcoming interviews.

Steps:

  1. Create a method findNumOfOccurrence(String str, char ch) which takes two parameters i.e. String and char
  2. In the method, convert the String to char[] using str.toCharArray()
  3. Declare a variable, int count = 0; which will count the Number of Occurrences of the specific character
  4. Next, use enhanced for loop to iterate each character from the String str
  5. Write if condition to check whether the specific character matches with the character in the String
  6. If the character matches, then the count will increase by 1
  7. Finally, we will write the return statement, which will return the count of that specific character
  8. For instance, we can call this method in the main method and use System.out.println(findNumOfOccurrence(“Hello World”, ‘o’)) to print the number of occurrences of the specific character i.e. ‘o’ in the String – “Hello World”

Java Program:

package TestAutomationCentral;

public class NumOfOccurrence {
    public static void main(String[] args) {
        //Java program that counts the number of occurrences
        // of a specific character in a string
        System.out.println(findNumOfOccurrence("Hello World", 'o'));
        System.out.println(findNumOfOccurrence("TestAutomationCentral", 'T'));

    }
    public static int findNumOfOccurrence(String str, char ch) {
        char[] arr = str.toCharArray();
        int count = 0;
        for (char c : arr) {
            if (ch == c) {
                count++;
            }
        }
        return count;
    }
}

Output:

2
1
Share

Leave a Reply