In this tutorial, we will learn to print the character which occurs the most. For any input string, we have to check the number of occurrences of each character and print the character with the maximum number of occurrences.
For example
Case1: If the user enters the string ‘Python is fun’
The output should be ‘n’, as the character ‘n’, occurs 2 times which is maximum in all other character occurrences in the string.
Case2: If the user enters the string ‘Engineer’
The output should be ‘e’, as the characters ‘e’, occurs 3 times which is maximum in all other character occurrences in the string.
Java Program to Print Maximum Occurred Character in String
import java.util.*;
public class Main {
public static void main(String[] args) {
int max_count = 0;
char max_char = Character.MIN_VALUE;
System.out.println("Java program to find maximum occured Character");
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a String");
String str = sc.nextLine();
int[] arr = new int[256];
for (int i = 0; i < str.length(); i++) {
arr[str.charAt(i)]++;
}
for (int i = 0; i < 256; i++) {
if (arr[i] > max_count) {
max_count = arr[i];
max_char = (char) i;
}
}
System.out.println(max_char + " occured maximum of " + max_count + " times");
}
}
Output
Java program to find maximum occured Character
Please enter a String
Hitechpoints Website
e occured maximum of 3 times
Explanation
In this output, for the input string ‘Quescol Website’, the array input elements as {‘H’, ‘i’, ‘t’, ‘e’, ‘c’, ‘h’, ‘p’, ‘o’, ‘i’, ‘n’, ‘t’, ‘s’,‘ ‘, ‘W’, ‘e’, ‘b’, ‘s’, ‘i’, ‘t’, ‘e’}. max_count returns the elements which appears maximum times as the element of array which is ‘e’ in this case repeated 3 times.