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.
Explanation:
- String and Edge Cases: First, check if the string is
nullor empty to handle edge cases. - Character Array: Convert the string to a character array for easier manipulation.
- Flag: Use a boolean
capitalizeNextto track whether the next character should be capitalized. - Loop through Characters: Iterate through each character, capitalize if
capitalizeNextis true, and append toStringBuilder. - 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.
Explanation:
- Split Words: Use regex to split the string by whitespace.
- Stream Processing: Use
mapto transform each word by capitalizing the first character. - 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.
Explanation:
- WordUtils: The
capitalizemethod ofWordUtilshandles 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:
| Method | Approach | Additional Libraries Required | Complexity | Code Conciseness |
| StringBuilder and Character | Iterative character manipulation | No | O(n) | Moderate |
| Java 8 Streams | Functional, using streams | No | O(n) | Concise |
| Apache Commons Text | Pre-built utility for capitalization | Yes | O(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.

