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.