Home / Programs / Write a Java program to count how many times a value appears in an array.
🚀 Programming Example

Write a Java program to count how many times a value appears in an array.

👁 21 Views
💻 Practical Program
📘 Step Learning
Learn this program step-by-step with algorithm, source code, output and detailed explanation.

📌 Information & Algorithm

Given Input:

Enter value to count: 10

Expected Output:

Occurrence count: 3

💻 Program Code

import java.util.Scanner;

class CountOccurrences {
    public static void main(String[] args) {
        int[] arr = {10, 20, 10, 30, 10, 40};
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter value to count: ");
        int key = sc.nextInt();

        int count = 0;

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == key) {
                count++;
            }
        }

        System.out.println("Occurrence count: " + count);
    }
}

                        

📘 Explanation

The program checks every element of the array and increases the counter whenever the value matches.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.