String Java Programs

Java Program to count occurrences of given character in string

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

How this Java program will behave?

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 “Hitechpoints 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.in);
        System.out.print("Please give a String : ");  
        String str= sc.nextLine();  
        Scanner sc1= new Scanner(System.in);
        System.out.print("Please give a char to count occurence: ");  
        char ch= sc1.next().charAt(0);
        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);
            if(arr[i]==ch){
                count++;
            }
        }
        return count;
    }
}   

Output

Please give a String : Hitechpoints
Please give a char to count occurence: i
Total Number of occurence of 'i' is: 2

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs