![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to print the maximum occurred character of a string in Java?
A String class can be used to represent the character strings, all the string literals in Java programs are implemented as an instance of the String Class. The Strings are constants and their values cannot be changed (immutable) once created.
In the below program, we can print the maximum occurred character of a given string.
Example
public class MaxOccuredCharacterTest { public static void main(String[] args) { String str1 = maxOccuredChar("tutorialspoint"); System.out.println(str1); String str2 = maxOccuredChar("AABBAABBCCAABBAA"); System.out.println(str2); String str3 = maxOccuredChar("111222333444333222111"); System.out.println(str3); } public static String maxOccuredChar(String str) { char[] array = str.toCharArray(); int maxCount = 1; char maxChar = array[0]; for(int i=0, j=0; i < str.length()-1; i=j) { int count = 1; while(++j < str.length() && array[i] == array[j]) { count++; } if (count > maxCount) { maxCount = count; maxChar = array[i]; } } return (maxChar + " = " + maxCount); } }
Output
t = 1 A = 2 1 = 3
Advertisements