Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

Anna

A 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:

Berlin

Every 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 Sea

Common 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 0

Check isEmpty() before taking the first character.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.