We are uploading our contents, please refresh app.
Java Premium

write a program in Java Program to Find the Frequency of Character in a String

In this program, you'll learn to find the occurrence (frequency) of a character in a given string.


Program:
import java.util.*;
public class Frequency 
{
   public static void main(String[] args) 
   {
        String str;
        char ch;
        int frequency = 0;
Scanner sc=new Scanner(System.in);
System.out.println("Input a sentence:");
  str=sc.nextLine();
System.out.println("Input a character to show how many times present:");
  ch=sc.next().charAt(0);
        for(int i = 0; i < str.length(); i++) {
            if(ch == str.charAt(i)) {
                ++frequency;
            }
        }
        System.out.println("Frequency of " + ch + " = " + frequency);
    }
}
Output:
Input a sentence:
welcome to java programming
Input a character to show how many times present:
m
Frequency of m = 3

  1. In the above program, the length of the given string, str, is found using the string method length().
  2. We loop through each character in the string using charAt() function which takes the index (i) and returns the character in the given index.
  3. We compare each character to the given character ch. If it's a match, we increase the value of frequency by 1.
  4. In the end, we get the total occurence of a character stored in frequency and print it.

Online user

Download our android app Download App Submit your query
x

Get Updates On

Java & Premium Programs

Java Solved & Questions

Java Coding easy to use

Proper Coding

Straight Into Your INBOX!

We are going to send you our resources for free. To collect your copy at first, join our mailing list. We are promising not to bother you by sending useless information. So don't miss any updates, stay connected!