Popular Tutorials
Start Learning JavaCertification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
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.
To understand this example, you should have the knowledge of the following Java programming topics:
Example: Find Frequency of Character
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
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 occurrence of a character stored in frequency and print it.
Did you find this article helpful?