Java
String Manipulation
Programming
Capitalize Letters
Coding Techniques

How to capitalize the first letter of word in a string using Java?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Capitalizing the first letter of each word in a string is a common requirement in text formatting, such as creating titles, headlines, or properly formatting user inputs. In Java, there are several ways to achieve this, utilizing different Java APIs and libraries. This article covers various methods to capitalize the first letter of each word in a string, detailing the technical aspects and providing examples for better understanding.

Using Core Java

Method 1: Using StringBuilder and Character

This method involves iterating through each character in the string, capitalizing the first letter of each word, and rebuilding the string using a StringBuilder.

java
1public class CapitalizeWords {
2    public static String capitalize(String str) {
3        if (str == null || str.isEmpty()) {
4            return str;
5        }
6
7        StringBuilder capitalizedString = new StringBuilder();
8        char[] charArray = str.toCharArray();
9        boolean capitalizeNext = true;
10
11        for (char c : charArray) {
12            if (Character.isWhitespace(c)) {
13                capitalizeNext = true; // Reset flag for next word
14            } else if (capitalizeNext) {
15                c = Character.toUpperCase(c); // Capitalize the first letter
16                capitalizeNext = false;
17            }
18            capitalizedString.append(c);
19        }
20
21        return capitalizedString.toString();
22    }
23
24    public static void main(String[] args) {
25        String input = "java programming language";
26        System.out.println(capitalize(input));
27    }
28}

Explanation:

  1. String and Edge Cases: First, check if the string is null or empty to handle edge cases.
  2. Character Array: Convert the string to a character array for easier manipulation.
  3. Flag: Use a boolean capitalizeNext to track whether the next character should be capitalized.
  4. Loop through Characters: Iterate through each character, capitalize if capitalizeNext is true, and append to StringBuilder.
  5. Return Result: Construct and return the final capitalized string.

Using Java 8 Streams

Java 8 introduced streams, which provide a functional approach to manipulate collections and datasets.

java
1import java.util.Arrays;
2import java.util.stream.Collectors;
3
4public class CapitalizeUsingStreams {
5    public static String capitalize(String str) {
6        if (str == null || str.isEmpty()) {
7            return str;
8        }
9
10        return Arrays.stream(str.split("\\s+"))
11                     .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase())
12                     .collect(Collectors.joining(" "));
13    }
14
15    public static void main(String[] args) {
16        String input = "java programming language";
17        System.out.println(capitalize(input));
18    }
19}

Explanation:

  1. Split Words: Use regex to split the string by whitespace.
  2. Stream Processing: Use map to transform each word by capitalizing the first character.
  3. Concatenate Strings: Collect transformed words into a single string with spaces in between.

External Libraries

Apache Commons Text

Apache Commons provides a utility class WordUtils that can be used for capitalizing words.

java
1import org.apache.commons.text.WordUtils;
2
3public class CapitalizeWithCommons {
4    public static void main(String[] args) {
5        String input = "java programming language";
6        String capitalized = WordUtils.capitalize(input);
7        System.out.println(capitalized);
8    }
9}

Explanation:

  • WordUtils: The capitalize method of WordUtils handles word capitalization, making it a concise and easy-to-use method.

Comparison and Summary

Here's a table summarizing the key points of each method:

MethodApproachAdditional Libraries RequiredComplexityCode Conciseness
StringBuilder and CharacterIterative character manipulationNoO(n)Moderate
Java 8 StreamsFunctional, using streamsNoO(n)Concise
Apache Commons TextPre-built utility for capitalizationYesO(n)Very Concise

Conclusion

By understanding these different methods of capitalizing the first letter of each word in a string, you enhance your ability to handle text processing tasks efficiently in Java. Each method has its own strengths, and the choice depends on your specific requirements, including performance, readability, and external dependencies. While core Java methods provide a deep understanding, using external libraries can significantly reduce code complexity in real-world applications.


Course illustration
Course illustration

All Rights Reserved.