import java.util.*;
class WordsCount
{
public static void main(String arg[])
{
int word=1;
Scanner in=new Scanner(System.in);
System.out.println(“Enter your sentence:[Try to ignore space at end]”);
String str=in.nextLine();
for(int i=0;i<str.length();++i)
{
if(str.charAt(i)==’ ‘)
word++;
}
System.out.println(“Number of words=”+word);
}
}
Count Number of Words in a String in Java
Counting the number of words in a string is one of the most common Java programming interview questions for beginners. This program helps students understand string handling, loops, arrays, and conditional statements in Java.
In Java, a word is usually separated by spaces. We can count the total number of words in a string using different approaches such as the split() method, loops, or character traversal.
This tutorial explains multiple ways to count the number of words in a string in Java with proper examples and output.
What is a Word Count Program in Java?
A word count program counts how many words are present inside a string.
Example:
Input:
Java is a programming language
Output:
5
The program counts all words separated by spaces.
Method 1: Count Words Using split() Method
The split() method is one of the easiest ways to count words in Java.
Java Program
public class WordCount {
public static void main(String[] args) {
String str = "Java is a programming language";
String[] words = str.trim().split("\\s+");
int count = words.length;
System.out.println("Total number of words: " + count);
}
}
Output
Total number of words: 5
Explanation
- trim() removes extra spaces from the beginning and end of the string.
- split(“\s+”) separates words using spaces.
- words.length returns the total number of words.
Method 2: Count Words Using Loop
We can also count words manually using loops and conditions.
Java Program
public class WordCountLoop {
public static void main(String[] args) {
String str = "Java programming language";
int count = 1;
for(int i = 0; i < str.length(); i++) {
if(str.charAt(i) == ' ') {
count++;
}
}
System.out.println("Total number of words: " + count);
}
}
Output
Total number of words: 3
Explanation
- The loop checks every character in the string.
- Whenever a space is found, the word counter increases.
- Total spaces + 1 gives the number of words.
Method 3: Count Words Using User Input
This method allows users to enter their own string.
Java Program
import java.util.Scanner;
public class WordCountInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
String str = sc.nextLine();
String[] words = str.trim().split("\\s+");
System.out.println("Total number of words: " + words.length);
}
}
Output
Enter a string:
Java is easy to learn
Total number of words: 5
Why Use trim() in Java?
The trim() method removes unnecessary spaces from the beginning and end of the string.
Without trim(), extra spaces may produce incorrect word counts.
Example:
" Java Programming "
After using trim():
"Java Programming"
Understanding split(“\s+”)
The expression:
split("\\s+")
means:
\\s→ whitespace character+→ one or more spaces
This helps handle multiple spaces correctly.
Time Complexity
The time complexity of the word count program is:
O(n)
Where:
nis the total number of characters in the string.
The program checks each character only once.
Real-World Uses of Word Count Program
Word count programs are used in:
- Text editors
- Search engines
- Content analysis tools
- SEO tools
- Blogging platforms
- Data processing applications
Common Mistakes Made by Beginners
1. Not Using trim()
Extra spaces may increase the word count incorrectly.
2. Using split(” “)
Using a single space may fail when multiple spaces exist.
Correct approach:
split("\\s+")
3. Forgetting Empty String Check
Always validate empty strings in real applications.
Interview Questions Related to Word Count in Java
Interviewers may ask:
- How does split() work in Java?
- What is the difference between split(” “) and split(“\s+”)?
- How do you count words without using split()?
- How do you handle multiple spaces?
FAQ’s
What is the easiest way to count words in Java?
Using the split() method is the easiest and most common approach.
Why is split(“\s+”) better than split(” “)?
It handles multiple spaces correctly.
Can we count words without split()?
Yes, we can count spaces manually using loops.
Which Java concept is used in this program?
This program uses strings, arrays, loops, and conditional statements.
Conclusion
The word count program in Java is an important beginner-level programming example. It helps students understand string handling, loops, arrays, and input processing in Java.
Using split(“\s+”) is the most efficient and beginner-friendly way to count the number of words in a string. Students should also practice loop-based approaches to improve their logic-building skills.
