How to count the occurrence of the given character in a string in java?

Let’s assume the string is apple and the given character is p to count the occurrence then the output of this program should be as follow:

p => 2 times


package com.javacodepoint.programs;

import java.util.Scanner;

public class CountGivenCharacter {

	// Main method
	public static void main(String[] args) {

		// String variable to take a string input from the user
		String str = null;

		char ch;
		int count = 0;

		// Creating scanner class object for reading user input
		Scanner sc = new Scanner(;

		System.out.println("Please enter a string to count the given character: ");

		// reading the string input
		str =;

		System.out.println("Please enter a character to count: ");

		// reading the character input
		ch =;

		// iterate the string from beginning to end
		for (int i = 0; i < str.length(); i++) {

			if (ch == str.charAt(i)) {


		// Printing the result
		System.out.println(ch + " => " + count +" times");




Please enter a string to count the given character:
Please enter a character to count:
e => 2 times

Java logical programs list

Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *