How to Count Occurrence in Java?

How to count occurrence of a specific character in a string using Java. A step-by-step guide with code examples for beginners and software testers. Perfect for interview preparation.

Welcome back to Testers Journey! Today, we’re diving into a commonly asked interview question: How do you find out how many times a specific character appears in a string in Java? Whether you’re preparing for an interview or just brushing up on your coding skills, this guide will help you understand the concept with a simple code example.

In this post, we’ll break down the problem, explain the logic step-by-step, and provide a Java code solution. And, as always, we’ll keep it simple and easy to follow. So, let’s get started!

How To Count Occurrences of a character in String

Why is This Topic Important?

You might be wondering, “Why do I need to know this?” Well, this question is a favorite among Interviewers because it tests your understanding of loops, string manipulation, and conditional statements—all fundamental concepts in programming. Plus, it’s a great way to showcase your problem-solving skills.

By the end of this post, you’ll be able to tackle this problem with confidence and understand the logic behind each step of the code. So, let’s break it down!

Problem Statement

Given a string, we want to count how many times a specific character appears in it. For example, in the string "testers journey", if we want to count the occurrence of the letter 'e', the output should be 4.

Solution: Step-by-Step Breakdown

We’ll use a simple approach for this problem:

  1. Initialize a count variable to keep track of the number of times the target character appears.
  2. Loop through each character in the string.
  3. Check if the current character matches the target character.
  4. If it matches, increment the count by one.
  5. Finally, print out the result.

Java Code Example

Let’s put the above logic into action with a Java code snippet:

public class CharOccurrence {
    public static void main(String[] args) {
        String input = "testers journey"; // The string we want to search
        char targetChar = 'e'; // The character we are counting
        int count = 0; // Variable to store the number of occurrences
        
        for (int i = 0; i < input.length(); i++) { // Loop through each character
            if (input.charAt(i) == targetChar) { // Check if it matches the target character
                count++; // If yes, increase the count
            }
        }
        
        System.out.println("The character '" + targetChar + "' appears " + count + " times in the string."); // Print the result
    }
}

Code Explanation

Let’s break down the code step-by-step so that you can understand what each line is doing:

  1. String input = "testers journey";
    • We’ve declared a string variable named input and assigned it the value "testers journey". This is the string in which we want to count the occurrence of the character.
  2. char targetChar = 'e';
    • We define a character variable called targetChar and set it to 'e'. This is the character we’re counting.
  3. int count = 0;
    • We initialize an integer variable called count with a value of 0. This variable will store the number of times the target character appears in the string.
  4. for (int i = 0; i < input.length(); i++) {
    • We use a for loop to go through each character of the string. i starts at 0 and goes up to the length of the string minus one.
  5. if (input.charAt(i) == targetChar) {
    • Inside the loop, we use an if statement to check if the character at the current position i in the string (input.charAt(i)) matches our target character. If it matches, we move on to the next step.
  6. count++;
    • If the character matches, we increment the count by 1. This keeps track of how many times we’ve seen the target character so far.
  7. System.out.println("The character '" + targetChar + "' appears " + count + " times in the string.");
    • Finally, we print out the result using System.out.println. This line displays how many times the target character appears in the string.

Why This Approach?

This approach is simple and easy to understand, especially for beginners. We use a for loop to check each character one by one, making it easy to see how the count increases with each occurrence of the target character

Conclusion

And that’s it! We’ve successfully counted the occurrences of a specific character in a string using a basic approach in Java. This is a great starting point for understanding string manipulation and looping in Java.

Be sure to check out more articles on Testers Journey Blogs :-

Don’t forget to check out our video tutorial on this topic on our YouTube channel. If you have any questions or suggestions for future topics, drop a comment below!

For more tutorials and insights, follow along on our Blogs, YouTube channel and Facebook Page. Happy coding!

Add a Comment

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