Java Program to Count Occurrence of Word in Sentence

« Previous Program Next Program »

Count Word in Sentence

To count the occurrence of all the words present in a string/sentence in Java Programming, first, you have to ask to the user to enter the sentence and start counting all the words with present in the given string/sentence using the method countWords() as shown in the following program.

Java Programming Code to Count Occurrence of Word in Sentence

Following Java Program ask to the user to enter/write a sentence, to count the total number of words in the sentence, then display the result on the screen. This is a simple program which will count all the words of simple sentence:

/* Java Program Example - Count Occurrence of Word in Sentence */
import java.util.Scanner;

public class JavaProgram
   public static int countWords(String str)
        int count = 1;
        for(int i=0; i<=str.length()-1; i++)
            if(str.charAt(i) == ' ' && str.charAt(i+1)!=' ')
        return count;
   public static void main(String args[])
        String sentence;
        Scanner scan = new Scanner(;
        System.out.print("Enter a Sentence : ");
        sentence = scan.nextLine();
        System.out.print("Total Number of Words in Entered Sentence is " + countWords(sentence));

When the above Java Program is compile and executed, it will produce the following output:

Java Program count number of words in sentence

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:

Java Online Test

« Previous Program Next Program »

© Copyright 2021. All Rights Reserved.