English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Program to Convert the First Character of a Sentence to Uppercase

To convert the first character of the sentence to uppercase, we must first separate each word in the sentence, then represent the first character of each word in uppercase, and then we must separate each word again and separate them with spaces to reconstruct the sentence.

Now let's complete each task one by one. First, to separately obtain each word in the sentence, we will use Java's Scanner class and implement its hasNext method to check if there are any words left in our sentence. If there is a word, we will obtain the word by using the next method of the same class.

After obtaining each word in the sentence, we now use the toUpperCase method of the Character class to convert the first character of each word to uppercase, and then use the substring method of the string class to concatenate the other characters of the word, and add a space at the end of each word to make them a sentence again.

Example

import java.util.Scanner;
public class UpperCaseOfSentence {
   public static void main(String[] args) {
      String upper_case_line = "";
      String str = "Lam is a good boy.";
      Scanner lineScan = new Scanner(str);
      while(lineScan.hasNext()) {
         String word = lineScan.next();
         upper_case_line += Character.toUpperCase(word.charAt(0)) + word.substring(1) + " ";
      }
      System.out.println(upper_case_line);
   }
}

Output Result

Lam is a good boy.