Home Java Java-tips Data Strings Q-pr-string-if Capitalize - Solution

Ask Questions?

View Latest Questions



Capitalize - Solution
Posted on: July 26, 2006 at 12:00 AM
Capitalize programming exercise.

Java: Capitalize - Solution

See Exercise - Capitalize programming exercise.

Method to change the first character to uppercase.

public static String capitalize(String s) {
    if (s.length() == 0) {
        return s;
    } else {
        return s.substring(0,1).toUpperCase() + s.substring(1);

For the extra credit part, just an a null test to the if statement.

    if (s == null || s.length() == 0) {

Because of short circuit evaluation, if s is null, the "or" operation is true and it doesn't even have to evaluate the second part, and therefore the null won't cause a NullPointerException.

Copyleft 2005 Fred Swartz MIT License