Convert to Title Case in Java

Convert a sentence to title case (first letter of each word uppercase).

BeginnerModule 4: String ProgramsExample 16 of 25
convert-to-title-case.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Enter a sentence: ");
7 String s = sc.nextLine().toLowerCase();
8
9 String[] words = s.trim().split("\\s+");
10 StringBuilder sb = new StringBuilder();
11 for (String w : words) {
12 if (w.isEmpty()) continue;
13 sb.append(Character.toUpperCase(w.charAt(0)))
14 .append(w.substring(1))
15 .append(" ");
16 }
17 System.out.println("Title case: " + sb.toString().trim());
18 sc.close();
19 }
20}

Output

Enter a sentence: java is awesome
Title case: Java Is Awesome

What's going on

We lowercase the sentence, then uppercase the first character of each word.