Find the Frequency of a Character in a String in Java

Exercise:

Write a Java Program to find the frequency of a character in a string.

Click Here to View the Solution
public class FrequencyCalculator {
  
     public static void main(String[] args) {
         String str = "This is my first java program";
         char ch = 'i';
         int frequency = 0;
  
         for(int i = 0; i < str.length(); i++) {
             if(ch == str.charAt(i)) {
                 ++frequency;
             }
         }
        System.out.println("Frequency of " + ch + " = " + frequency);
     }
 } 
Click Here to View the Output!
Frequency of i = 3
Click Here to View the Explanation!
  • In this program, the length of str which is a variable of string type, is determined by a string method called length().
  • Every character present in the string is iterated through the charAt() function. This function accepts an index (i) as its input and outputs the corresponding character which is placed on that index in the string sequence.
  • The character for which the frequency must be calculated for, is stored in the ch variable. This variable is matched against every character in the string, and if a match is found, an increment of 1 occurs in the frequency variable.
  • By the end of this program, the total count or the frequency of a character occurring in a string is fetched from the frequency variable which is then printed on the screen.

%d bloggers like this: