1. Introduction
Finding the maximum occurring character in a string is a common task in Java, which can be used in various applications such as text analysis and natural language processing. This task involves analyzing a string to determine which character appears most frequently. In this guide, we will use a HashMap to achieve this by storing the frequency of each character and then determining the character with the highest frequency.
2. Program Steps
1. Define a string for which we want to find the maximum occurring character.
2. Create a HashMap to store the frequency of each character in the string.
3. Traverse the string and populate the HashMap with character frequency.
4. Initialize variables to keep track of the maximum occurring character and its frequency.
5. Iterate through the HashMap to find the character with the highest frequency.
6. Print the maximum occurring character and its frequency.
3. Code Program
import java.util.HashMap;
import java.util.Map;
public class MaxOccurringCharacter {
public static void main(String[] args) {
// Step 1: Define a string for which we want to find the maximum occurring character
String inputString = "java programming";
// Step 2: Create a HashMap to store the frequency of each character in the string
Map<Character, Integer> charCountMap = new HashMap<>();
// Step 3: Traverse the string and populate the HashMap with character frequency
for (char c : inputString.toCharArray()) {
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}
// Step 4: Initialize variables to keep track of the maximum occurring character and its frequency
char maxChar = ' ';
int maxCount = 0;
// Step 5: Iterate through the HashMap to find the character with the highest frequency
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
if (entry.getValue() > maxCount) {
maxCount = entry.getValue();
maxChar = entry.getKey();
}
}
// Step 6: Print the maximum occurring character and its frequency
System.out.println("The maximum occurring character is '" + maxChar + "' with a frequency of " + maxCount);
}
}
Output:
The maximum occurring character is 'g' with a frequency of 2
4. Step By Step Explanation
Step 1: We initialize the string inputString for which we will determine the maximum occurring character.
Step 2: We create a HashMap called charCountMap that will store each character of the string