Java Program to count occurrences of a character in a string

In this tutorial we will learn how to write program in Java to count occurrence of character in a String.


Also Read this:  C program to count the occurrence of a character in String.

This Java program will take a string and a character as an input. And it will count the  occurrence of a given character. This program will also count spaces I we will give it.


For example:

If we have given a String as an input “Quescol is educational website” and also a character ‘s’.

Then after counting character ‘a’, program will return output 2.

Method to count the occurrence of given character in a string using Java.

import java.util.*;  
public class Main {  
    public static void main(String[] args) {  
        Scanner sc= new Scanner(;
        System.out.print("Please give a String : ");  
        String str= sc.nextLine();  
        Scanner sc1= new Scanner(;
        System.out.print("Please give a char to count occurence: ");  
        char ch=;
        System.out.print("Total Number of occurence of '"+ch+"' is: "); 
        System.out.println(countOccurence(str, ch));
    public static int countOccurence(String str, char ch){
        char arr[] = new char[str.length()]; 
        int count=0;
        for(int i=0; i<str.length();i++ ){
            arr[i] = str.charAt(i);
        return count;


count occurrences of character in string java

Leave a Comment