Java Program to Count Frequency of Each Character in a String

In this java program I am counting the frequency of each character in a string. I have used very simple logic, if still you are facing any problem to understand this then you can ask you queries in the comment section.

Java Program to Count Frequency of Each Character in a String

import java.util.Scanner;

class Frequency
{
 public static void main(String...s)
 {
  String str="";
  int count=0,len=0,flag=0;

  Scanner sc=new Scanner(System.in);
  System.out.print("nEnter a string:");
  
  str=sc.nextLine();
  len=str.length();
  
  for(int i=0;i<len;++i)
  {
   count=0;
   for(int j=0;j<len;++j)
    if(str.charAt(j)==str.charAt(i))
     count++;

   for(int k=0;k<i;++k)
    if(str.charAt(k)==str.charAt(i))
     flag=1;

   if(flag!=1)
    System.out.print(str.charAt(i)+":"+count+"n");

   flag=0;
  }
 }
}  

Java Program to Count Frequency of Each Character in a String

5 thoughts on “Java Program to Count Frequency of Each Character in a String”

Leave a Comment

Your email address will not be published. Required fields are marked *