Java Program to Find the Frequency of a Character

In this tutorial, we will write a program to calculate the frequency of Characters present in a String in java.

Frequency refers to the number of times that have occurred. In this program, we will count how many times each character is repeated in a String and display the result for each word’s frequency.

The program splits each word with space count present after every word, toCharArray() function is used in the following java program.

Although if you want to know about the String and loop that are used in the program below. you may click the link below:

We will see two examples:

1. Where the String is already defined in the program.
2. Where the string is taken as an input from the user.


1. Program to find the frequency of Words in Java

//find a frequency of a character 

public class FrequencyOfCharacter
{
  public static void main(String[] args)
  {
    int i, j;
    String str = "Beautiful Beach";
    int[] frequency = new int[str.length()];

    char string[] = str.toCharArray();

    for (i = 0; i < str.length(); i++)
    {
      frequency[i] = 1;
      for (j = i + 1; j < str.length(); j++)
      {
        if (string[i] == string[j])
        {
          frequency[i]++;

         	//Set string[j] to 0  
          string[j] = '0';
        }
      }
    }

    //Displays the characters with their frequency    
    System.out.println("Following Lists the characters and their frequency:");
    for (i = 0; i < frequency.length; i++)
    {
      if (string[i] != ' ' && string[i] != '0')
        System.out.println(string[i] + "->" + frequency[i]);
    }
  }
}

Output:

Following Lists the characters and their frequency:
B->2
e->2
a->2
u->2
t->1
i->1
f->1
l->1
c->1
h->1

2. Program to find the frequency of Words in Java, user’s input

//find a frequency of a character 

import java.util.Scanner;

public class FrequencyOfCharacter
{
  public static void main(String[] args)
  {
    int i, j;
    String str;
    Scanner sc = new Scanner(System.in);

    //User Input
    System.out.println("Enter a string: ");
    str = sc.nextLine();

    int[] frequency = new int[str.length()];

    char string[] = str.toCharArray();

    for (i = 0; i < str.length(); i++)
    {
      frequency[i] = 1;
      for (j = i + 1; j < str.length(); j++)
      {
        if (string[i] == string[j])
        {
          frequency[i]++;

          //Set string[j] to 0  
          string[j] = '0';
        }
      }
    }

    //Displays the characters with their frequency    
    System.out.println("Following Lists the entered characters and their frequency:");
    for (i = 0; i < frequency.length; i++)
    {
      if (string[i] != ' ' && string[i] != '0')
        System.out.println(string[i] + "->" + frequency[i]);
    }
  }
}

Output:

Enter a string: 
Beautiful Beach
Following Lists the characters and their frequency:
B->2
e->2
a->2
u->2
t->1
i->1
f->1
l->1
c->1
h->1