Java Program to Find the Frequency of Character in a String

In this program, you’ll learn to find the occurence (frequency) of a character in a given string.

 

Example: Find the Frequency of Character

  1. public class Frequency {
  2. public static void main(String[] args) {
  3. String str = "This website is awesome.";
  4. char ch = 'e';
  5. int frequency = 0;
  6. for(int i = 0; i < str.length(); i++) {
  7. if(ch == str.charAt(i)) {
  8. ++frequency;
  9. }
  10. }
  11. System.out.println("Frequency of " + ch + " = " + frequency);
  12. }
  13. }

When you run the program, the output will be:

Frequency of e = 4

In the above program, the length of the given string, str, is found using the string method length().

We loop through each character in the string using charAt() function which takes the index (i) and returns the character in the given index.

We compare each character to the given character ch. If it’s a match, we increase the value of frequency by 1.

In the end, we get the total occurence of a character stored in frequency and print it.