Home » Java programs

Java program to count number of words in a sentence

In this Java program, we will learn how to count the number of uppercase and lowercase letters in a given string?
Submitted by Jyoti Singh, on October 05, 2017

Given a sentence and we have to count total number of words using Java program.


Input sentence: "I love programming"
Number of letters: 3

In this code we have one input:

A string input (It will be a sentence entered by the user which needs to be checked).

For each string we will have two outputs

The number of words in sentence

Consider the program: It will take number of inputs, sentences or string and print total number of words.

import java.util.Scanner;

public class ToCountNumberOfWords{

	public static void main(String[] args) {
		//Scanner is a class used to get the output from the user
		Scanner Kb=new Scanner(System.in);
		//Input sentence from the user
		System.out.println("Enter a sentence!");
		/*hasNext is a function of Scanner class which checks whether the next line is present or not 
		if the line is present the code will continue to run 
		but if the next line is not present the code will be terminated
			//nextLine is a function of Scanner class to read the input line
			String line=Kb.nextLine();
			/* this string will contain the words that are split or we can say break by the split function
			split function takes parameter i.e from where we have to split the string
			here,that parameter is a space as soon as it will find a space,it will break that into substring from there
			and store them in string array arr with an index 
			String[] arr=line.split(" ");
			//counter to count the number of words initialized to zero
			int word=0;
			//looping to count the number of words in array 
			for(int i=0;i<arr.length;i++){
			//print the number of words in a sentence

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.

Comments and Discussions

We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.