How to capitalize the first letter
Short answer
Take the first character, upper-case it and append the rest of the string:
void main() {
String name = "anna";
String result = name.substring(0, 1).toUpperCase() + name.substring(1);
IO.println(result);
}Output:
AnnaA safe method
substring(0, 1) throws on an empty string, so check the length:
String capitalize(String text) {
if (text == null || text.isEmpty()) {
return text;
}
return Character.toUpperCase(text.charAt(0)) + text.substring(1);
}
void main() {
IO.println(capitalize("java"));
IO.println("[" + capitalize("") + "]");
}Output:
Java
[]The rest in lower case
If the string came in upper case, lowercase it first:
void main() {
String city = "BERLIN";
String lower = city.toLowerCase();
IO.println(lower.substring(0, 1).toUpperCase() + lower.substring(1));
}Output:
BerlinEvery word
Split the string into words, process each one and join them back:
void main() {
String title = "the old man and the sea";
String result = Arrays.stream(title.split(" "))
.map(word -> word.substring(0, 1).toUpperCase() + word.substring(1))
.collect(Collectors.joining(" "));
IO.println(result);
}Output:
The Old Man And The SeaCommon mistake
Calling substring(0, 1) on an empty string:
void main() {
String name = "";
IO.println(name.substring(0, 1).toUpperCase());
}Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Range [0, 1) out of bounds for length 0Check isEmpty() before taking the first character.
Functions used in this recipe
- String.substring() — Returns the part of a string between two indexes.
- String.toUpperCase() — Returns a copy of the string with all letters in upper case.
- String.charAt() — Returns the character at the given index.