Write a program to First alphabet capital of each word in given string


This is a Java program that takes a sentence as input from the user and capitalizes the first letter of each word in the sentence.

  • The program starts by creating a Scanner object to read input from the user. It then prompts the user to enter a sentence and reads the input using the nextLine() method of the Scanner class.
  • Next, the program creates a new empty string variable called upr_line, which will store the modified sentence with capitalized first letters. The program also creates a new Scanner object called line_scan to scan the sentence word by word.
  • The program then enters a loop that continues as long as there are more words in the sentence. In each iteration of the loop, the program reads the next word using the next() method of the line_scan object. It then capitalizes the first letter of the word using the toUpperCase() method of the Character class, concatenates it with the rest of the word using the substring() method, and adds a space to the end of the modified word. Finally, the modified word is added to the upr_line string variable.
  • After the loop completes, the program prints out the original sentence and the modified sentence with capitalized first letters using the println() method.

Source Code

import java.util.Scanner;
public class FirstAlphabet_Capital 
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter Sentence here : ");
		String l = input.nextLine();
		String upr_line = ""; 
 
		//The new line which is generated after conversion.
		Scanner line_scan = new Scanner(l); 
		while(line_scan.hasNext())
		{
			String word = line_scan.next(); 
			upr_line += Character.toUpperCase(word.charAt(0)) + word.substring(1) + " "; 
		}
 
		System.out.println("Given Sentence is : " +l); 
		System.out.println("Sentence after Convert : " +upr_line.trim()); 
	}
}

Output

Enter Sentence here : This is a Java
Given Sentence is : This is a Java
Sentence after Convert : This Is A Java

Example Programs