Java Program to Find the Frequency of Character in a String

Guys who are serious about learning the concepts of the java programming language should practice this list of programs in java and get a good grip on it for better results in exams or interviews.

Program to Find the Frequency of Character in a String

In this article we will see how we can find frequency of a character in a String.

Frequency of Character:

We know string is combination of characters. So, in a string it may happen that a particular string may occur only once or multiple times.

So in this program we will count how many times a character is occurring in a string.

For example:

"You are studying from BTechGeeks" is a string.
In which,
Character 'e' is present 4 times.
Character 'h' is present only once.
Character 'r' is present 3 times.

Let’s see the below approach how to do it.

Method: Find frequency of a character using for loop

By using for loop we can find the number of frequency of a particular character in a string.

Approach:

  • Take a character variable ch.
  • Take an integer variable count.
  • ch will contain the character of which you are finding frequency.
  • Initialize count with 0.
  •  Take a for loop and match the character of which you are finding the frequency with each character of the string.
  • During iteration if any characters matches then increment the count value.

Program:

public class Main
{

public static void main(String[] args)
{
String s = "You are studying from BTechGeeks";
char ch = 'e';
int count = 0;

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

System.out.println("Frequency of " + ch + " = " + count);
}
}
Output:

Frequency of e = 4

Are you seeking professional help for coding in the Java programming language? The tutorial of Java Programming Examples for beginners and experts will strongly improve your coding skills then you can program for any logic in Java.

Related Java Basic Programs: