Java Program to find the frequency of character in a string


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


Enter string: Hello

Enter a character: l

Total Frequency is: 2

Example: How to find the frequency of character in a string in java

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("Enter a char for frequency:");
        b = s.next().charAt(0);

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

        System.out.print("total occurrences '" + b + "' in String is :" + count);

    }
}

Output:

Enter a string:xiith
Enter a char for frequency:i
total occurrences 'i' in String is :2