English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive List of Java Examples
In this program, you will learn how to find the frequency of characters in a given string.
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); } }
When the program is run, the output is:
Frequency of e = 4
In the above program, the string method length() is used to find the length of the given string str.
We use the charAt() function to iterate over each character in the string, which accepts an index (i) and returns the character at the given index.
We compare each character with the given character ch. If a match is found, we increase the frequency value.1.
In the end, we get a total count of the occurrences stored in a character, and we print the value of frequency.