Count Words in Java: Explanation & Practice

Count words in a sentence

Problem summary

Write a program that counts the number of words in a sentence.

Starter code

public class Main {
    public static void main(String[] args) {
        String sentence = "Java is a programming language"; // Test case 1
        
        // Count words
        // Print: Word count: <result>
    }
}

Expected output and test cases

  • 5 words in sentence
    Word count: 5
  • Single word
    Word count: 1
  • Three words
    Word count: 3

Hints

  1. Split by space: .split(" ")
  2. Count array length after split
  3. Handle multiple spaces with .split("\\s+")

Related Strings exercises

Practice all Strings exercises · Run this idea in the Java compiler