Java Program to find frequency of character in a string


In this program, You will learn how to find frequency of character in a string in Java.


Enter string: Hello

Enter a character: l

Total Frequency is: 2


Example: How to find frequency of character in a string in Java

Run it Now
import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        Scanner s = new Scanner(System.in);
        String str;
        int j, i = 0, count = 0;
        char b;

        System.out.print("Enter a String :");
        str = s.nextLine();
        char a[] = str.toCharArray();

        for (j = 0; j < a.length; j++) {
            i++;
        }

        System.out.print("\nEnter a Char For Frequency :");
        b = s.next().charAt(0);

        for (j = 0; j < i; j++) {
            if (a[j] == b) {
                count++;
            }
        }

        System.out.print("\nThe Occurance of '" + b + "' in String is :" + count);

    }
}

Output:

Enter a String :Welcome to Xiith
Enter a Char For Frequency :t
The Occurance of 't' in String is :2