Below are three increasingly-robust ways to “capitalize the first letter” of a String in Java 21.
Pick the one that matches how bullet-proof you need the code to be.
1. Quick-and-dirty (ASCII only)
String capitalizeAscii(String s) {
if (s == null || s.isEmpty()) return s;
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
• Works for plain ASCII (A–Z)
• Fails for locale–specific cases (i → İ in Turkish) and for characters outside the BMP (e.g. emojis, some Asian scripts).
2. Locale-aware, BMP-only
String capitalize(String s, Locale locale) {
if (s == null || s.isEmpty()) return s;
return s.substring(0, 1).toUpperCase(locale) + s.substring(1);
}
• Handles language quirks (Locale.forLanguageTag("tr"))
• Still breaks if the first character is a supplementary code point (surrogate pair) because substring(0,1) grabs only half of it.
3. Fully Unicode-safe (recommended)
String capitalizeUnicode(String s, Locale locale) {
if (s == null || s.isBlank()) return s;
int firstCp = s.codePointAt(0); // full code point
int firstCpLength = Character.charCount(firstCp);
int titleCaseCp = Character.toTitleCase(firstCp); // locale-agnostic title case
StringBuilder out = new StringBuilder(s.length());
out.appendCodePoint(titleCaseCp) // first letter capitalized
.append(s.substring(firstCpLength)); // rest unchanged
return out.toString();
}
Why this is “best”:
- Handles any Unicode character (emoji, CJK, etc.).
- Avoids mangling surrogate pairs.
Character.toTitleCase gives the correct title-case mapping, which can differ from upper-case (e.g., “dz” → “Dz”).
- Works on every JDK since 1.5, no external libs.
If you also need the remainder of the string lower-cased (a common “Capitalize” expectation), just change the last line to:
.append(s.substring(firstCpLength).toLowerCase(locale));
Bonus: Regex one-liner (Java 9+)
String result = str.replaceFirst("^[\\p{Ll}]", m -> m.group().toUpperCase(locale));
Readable, Unicode-safe for the first code unit, but a tiny bit slower than the hand-rolled version.
External library shortcut
If you’re already using Apache Commons Text:
String cap = WordUtils.capitalize(str); // sentence case
Or Commons Lang:
String cap = StringUtils.capitalize(str); // first letter only
TL;DR
For production code in Java 21, use the Unicode-safe version (#3) unless you’re sure the input is plain ASCII and performance is critical.