# Frequently Asked Java Program 26: Java Program to Find Occurrence of Each Char in a Given String Without Using Collection

### Problem Statement:

Write a program to print occurrence of each character in given string without using Collection.

Example:-

Please enter the string to find occurrence of each char:
Make Selenium Easy
You entered: Make Selenium Easy
Occurrence of M : 2
Occurrence of A : 2
Occurrence of K : 1
Occurrence of E : 4
Occurrence of whitespace : 2
Occurrence of S : 2
Occurrence of L : 1
Occurrence of N : 1
Occurrence of I : 1
Occurrence of U : 1
Occurrence of Y : 1

### Problem Solution:

This problem is easy to solve with the help of Collection framework of Java but in interview, you might be asked to solve without using Collection framework.

#### Logic:

1. We will pick first char from given string and iterate through each char of String to match if same char is present. We will use a counter with default value as zero for each iteration. Counter will be incremented by one if occurrence of char is found.
2. We will replace the char with empty char at end of each iteration causing reduction in length of actual string.  Iteration will be continued till the length of String is greater than one.
3. When (If) length of string is equal to 1, print occurrence of last char  as one.
4. We will give name to whitespace (” “) as “Whitespace” for better readability of output.

### Output:

```Please enter the string to find occurrence of each char:
Make Selenium Easy
You entered: Make Selenium Easy
Occurrence of M : 2
Occurrence of A : 2
Occurrence of K : 1
Occurrence of E : 4
Occurrence of whitespace : 2
Occurrence of S : 2
Occurrence of L : 1
Occurrence of N : 1
Occurrence of I : 1
Occurrence of U : 1
Occurrence of Y : 1
==============================================================
Please enter the string to find occurrence of each char:
ABCDEF
You entered: ABCDEF
Occurrence of A : 1
Occurrence of B : 1
Occurrence of C : 1
Occurrence of D : 1
Occurrence of E : 1
Occurrence of F : 1
===============================================================
```

#HappyCoding

#### Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

## 1 thought on “Frequently Asked Java Program 26: Java Program to Find Occurrence of Each Char in a Given String Without Using Collection”

1. shabana khan says:

public class CharacterOccurenceInString {

public static void main(String[] args) {
countChars(“Make Selenium Easy”);

}
public static void countChars(String s)
{
s=s.toLowerCase();
int l1;
while(s.length()!=0)
{
l1=s.length();
String str=String.valueOf(s.charAt(0));

System.out.print(str+””);
s=s.replaceAll(str, “”);
int l2=s.length();

System.out.println(l1-l2);
}
}

}