Count Words in a Sentence in Java — Definition, Examples and Program

Learn how to count words in a sentence using Java. This blog explains the logic with examples, a clean Java program, and practice challenges for beginners.

Count Words in a Sentence in Java — Definition, Examples and Program

Counting words in a sentence is a common string problem. It helps in text analysis, document processing, and input validation.

In this blog, you will learn:

What Is a Word?

A word is a group of characters separated by spaces. Multiple spaces between words should not be counted as extra words.

How the Logic Works

To count words in a sentence:

  1. Ignore leading and trailing spaces.
  2. Count transitions from space to non-space characters.
  3. Each transition indicates the start of a new word.

Example 1

Input: "Java is fun"

Total Words: 3

Example 2

Input: " Learn Java Programming "

Total Words: 3

Java Program to Count Words


import java.util.Scanner;

public class CountWords {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a sentence: ");
        String sentence = sc.nextLine();

        int wordCount = 0;
        boolean isWord = false;

        for (int i = 0; i < sentence.length(); i++) {
            char ch = sentence.charAt(i);

            if (ch != ' ' && !isWord) {
                wordCount++;
                isWord = true;
            } else if (ch == ' ') {
                isWord = false;
            }
        }

        System.out.println("Number of words: " + wordCount);
    }
}

Sample Output


Enter a sentence: Java programming is powerful
Number of words: 4

Practice Challenges

  1. Count words without using any extra boolean variable.
  2. Count words using split() and compare both approaches.
  3. Find the longest word in a sentence.

Counting words accurately requires careful handling of spaces. This problem builds strong fundamentals in string traversal and condition handling.