</>

Technology

Java Programs

Difficulty

Beginner

Interview Question

Write a Java program to count the number of words in a string.

Answer

Count Words in a String

Java
import java.util.Scanner;

public class CountTheWords {
    public static void main(String[] args) {
        System.out.println("Enter the string:");

        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();

        int count = 1;

        for (int i = 0; i < s.length() - 1; i++) {
            if ((s.charAt(i) == ' ') && (s.charAt(i + 1) != ' ')) {
                count++;
            }
        }

        System.out.println("Number of words in a string = " + count);
    }
}

Sample Input/Output

CODE
Enter the string:
Java is a programming language
Number of words in a string = 5

Simpler Approach Using split()

Java
public class CountWordsSimple {
    public static void main(String[] args) {
        String s = "Java is a programming language";

        // split by one or more whitespace characters
        String[] words = s.trim().split("\\s+");
        System.out.println("Word count: " + words.length);  // → 5
    }
}

Handle Edge Cases

Java
public static int countWords(String s) {
    if (s == null || s.trim().isEmpty()) return 0;
    return s.trim().split("\\s+").length;
}

System.out.println(countWords(""));               // → 0
System.out.println(countWords("  hello  world ")); // → 2
System.out.println(countWords("Java"));            // → 1

Using StringTokenizer

Java
import java.util.StringTokenizer;

String s = "Java automation testing is fun";
StringTokenizer st = new StringTokenizer(s);
System.out.println("Word count: " + st.countTokens());  // → 5

Automation Testing Relevance

Java
// Count words in a web element's text
String elementText = driver.findElement(By.css(".description")).getText();
int wordCount = elementText.trim().split("\\s+").length;
assertTrue(wordCount > 10, "Description should have more than 10 words");

Follow AutomateQA