In Java, to print the frequency/occurrence of each character in a string, we can use ASCII values or collection frameworks like Maps.
For the input string “Java”, the occurrences of each character are: J-1, a-2, and v-1.
In this article we will learn how to count the frequency of each character in a string through an example, detailed logic and program explanation for better understanding.
Problem Statement
We need to write a Java program to print the frequency of each character in a given string. The program should take input string and output the number of times each character is repeated. Let’s see an example,
Example:
For a given input String str “Mam”, Output should be ” M-2 and a -1″
Explanation:
Input string "Mam":
To ensure consistency in counting character frequencies regardless of case sensitivity, we convert the entire string to uppercase, resulting in "MAM".
In "MAM":
'M' appears 2 times
'A' appears 1 time
Therefore, in the string "Mam", 'M' occurs twice and 'A' occurs once.
Logic to print the frequency of each character
There are multiple logics to print the frequency of each character in a given string in java programming language.
Logic 1: Using ASCII values
To print the frequency/occurrence of each character using ASCII values in Java:
- Take input String string from the user.
- Convert the input string to lowercase using toLowerCase() to ensure case insensitivity.
- Create an integer array ‘count’ of length 256 (int[] count = new int[256];) to store the frequency of each character. This assumes the use of ASCII characters, which range from 0 to 255.
- Iterate through each character in the input string using for loop. For each character, if it is not a space, increment the corresponding index in the count array.
- Using another for loop, Iterate through the count array, which represents ASCII characters.
- For each index with a frequency greater than 0, print the character (corresponding to the ASCII value) and its frequency.
Logic 2: Using Maps
To print the frequency of each character using Maps in Java:
- Take an input string from the user and store it in a variable str.
- Convert the input string str to uppercase to ensure case insensitivity.
- Initialize a HashMap named countMap to store the frequency of each character.
- The key of the map is the character, and the value is its frequency.
- Iterate through each character in the input text using a for loop. For each character:
- Check if it is not a space (using Character.isWhitespace()).
- Count its frequency using countMap.getOrDefault method to retrieve the current frequency of the character from the map. If the character is not already present, it defaults to 0.
- Update the map with the new frequency value by using countMap.Put() method to increment the current count.
- Use another for-each loop or iteration over the countMap.entrySet() to iterate over each entry (key-value pair) in the countMap.print() each character and its frequency.
Java program to print the frequency of each character
Program 1: Using ASCII values
In the below program we are using ASCII values to print the frequency of each character in a given string in Java.
import java.util.Scanner;
public class FrequencyCharacter {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the string");
String string = s.nextLine();
string = string.toLowerCase();
System.out.println("Character \t Occurrence");
int[] count = new int[256];
for (int i = 0; i < string.length(); i++) {
char ch = string.charAt(i);
if (ch != ' ') {
count[ch]++;
}
}
for (int i = 0; i < 256; i++) {
if (count[i] > 0) {
System.out.println(" "+(char)i+"\t\t"+" "+
count[i]);
}
}
s.close();
}
}
Output:
Enter the string
FreeLearn
Character Occurrence
a 1
e 3
f 1
l 1
n 1
r 2
đ§ Explanation:
- The java program uses a
Scanner
object to read input from the console. - After asking the user to input a string, it reads the input string.
- It converts the input string to lowercase using
string.toLowerCase()
. This ensures that the program counts the frequency of characters regardless of their case. - It prints the header for the output table, indicating “Character” and “Occurrence”.
- Initializes an array named
count
of size 256 to store the frequency of each ASCII character. This array will be used to store the frequency count for each character. - It iterates through each character of the input string using a for loop. For each character, it checks if it’s not a space. If it’s not a space, it increments the frequency count of that character in the
count
array. - After counting the frequency of each character, it iterates through the
count
array and prints out each character along with its frequency, if its frequency is greater than 0. - Finally, it closes the
Scanner
object to release system resources.
Program 2: Using Maps
In the below program we are using Maps to print the frequency of each character in a given string in Java.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class FrequencyCharacter1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a string");
String str = s.nextLine();
str=str.toUpperCase();
System.out.println("Character \t Occurrence");
Map<Character, Integer> countMap = new HashMap<>();
for (char characters : str.toCharArray()) {
if (characters != ' ') {
int count = countMap.getOrDefault(characters, 0);
countMap.put(characters, count + 1);
}
}
for (Map.Entry<Character, Integer> entry : countMap.entrySet()) {
System.out.println(entry.getKey() +"\t\t"+ " " +entry.getValue());
}
s.close();
}
}
Output:
Enter a string
Java
Character Occurrence
A 2
V 1
J 1
đ§ Â Explanation:
- The java program uses a
Scanner
object to read input from the console. - After asking the user to input a string, it reads the input String str.
- It converts the input str to uppercase using
str.toUpperCase()
. This ensures that the program counts the frequency of characters regardless of their case. - It prints the header for the output table, indicating “Character” and “Occurrence”.
- Program creates a
HashMap
namedcountMap
to store character-frequency pairs. - It iterates through each character of the input string using a for-each loop.
- For each character, it checks if it’s not a space. If it’s not a space, it retrieves the current frequency of the character from the
countMap
usinggetOrDefault
. If the character is not present, it defaults the count to 0. Then, it increments the frequency count by 1 and puts it back into thecountMap
. - After counting the frequency of each character, it iterates through the
countMap
and prints out each character along with its frequency. - Finally, it closes the
Scanner
object to release system resources.
Conclusion
In this article, we have learnt how to print the frequency of each character in a string in Java. We have seen the logic and implemented the program using ASCII values and Maps in Java. Hope this article helped you in the understanding of the program.
You can also check our other Java tutorials
- Java Program to swap first and last digit of a number
- Java program to print HCF (GCD) of two numbers
- Count the digits of a given number in Java
- Java program to print sum of prime numbers in a range
Happy Java Programming!1