Strings

Java Program to Find Frequency of Character

A Java program to find the frequency of a character in a string.

Problem Description

Write a Java program to find the frequency of a specific character in a given string.

Code

Frequency.java
public class Frequency {
    public static void main(String[] args) {
        String str = "This website is awesome.";
        char ch = 'e';
        int frequency = 0;

        for(int i = 0; i < str.length(); i++) {
            if(ch == str.charAt(i)) {
                ++frequency;
            }
        }

        System.out.println("Frequency of " + ch + " = " + frequency);
    }
}

Output

Frequency of e = 4

Explanation

  1. Loop: Iterate through each character of the string.
  2. Comparison: Check if the current character matches the target character.
  3. Counter: Increment if there's a match.