Write a Java program to count the frequency of each word in a string using a HashMap.

Split the string into words, then use a HashMap where the key is the word and the value is how many times it has appeared, incrementing the count for each word.

Key Points

import java.util.LinkedHashMap;
import java.util.Map;

public class WordFrequency {

    public static void main(String[] args) {
        String text = "Java is fun and Java is powerful and java is everywhere";

        Map<String, Integer> counts = new LinkedHashMap<>();
        for (String word : text.toLowerCase().trim().split("\\s+")) {
            counts.merge(word, 1, Integer::sum);
        }

        counts.forEach((word, count) -> System.out.println(word + " = " + count));
    }
}

Output

java = 3

is = 3

fun = 1

and = 2

powerful = 1

everywhere = 1

Good to Know

With streams the same result is Arrays.stream(words).collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())), which returns Long counts instead of Integer.

Mention case handling and punctuation before the interviewer asks; edge cases like "Java," versus "Java" are a common follow-up.

Common Mistakes

Follow-up Questions

Interview Tip

A concise interview answer is

I lower-case the text, split it on whitespace, and use map.merge(word, 1, Integer::sum) on a HashMap so each word's count is created or incremented in one step. It runs in O(n), and I use a LinkedHashMap if the output should keep the original word order.

Last updated: 11 November 2026

Previous question: Write a Java program to swap two variables without using a third variable.

Next question: Write a Java program to iterate a HashMap using a while loop and an enhanced for loop.

More Java Coding Questions interview questions

All Java Coding Questions questions