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("=== Find maximum occured Character in String ===");
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
=== Find maximum occured Character in String ===
Please enter a String
java code
a occured maximum of 2 times
Explanation
In this output, for the input string ‘Quescol Website’, the array input elements as {‘Q’, ‘u’, ‘e’, ‘s’, ‘c’, ‘o’, ‘l’, ‘ ‘, ‘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.