Java String Capitalize capitalize(String str)

Here you can find the source of capitalize(String str)

Description

Capitalize a String , changing the first letter to upper case as per Character#toUpperCase(char) .

License

Apache License

Parameter

Parameter Description
str the String to capitalize, may be null

Return

the capitalized String , or null if the supplied string is null

Declaration

public static String capitalize(String str) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**//from w ww.  j  av  a 2s . co m
     * Capitalize a {@code String}, changing the first letter to upper case as per {@link Character#toUpperCase(char)}. No other letters are changed.
     * 
     * @param str the {@code String} to capitalize, may be {@code null}
     * @return the capitalized {@code String}, or {@code null} if the supplied string is {@code null}
     */
    public static String capitalize(String str) {
        return changeFirstCharacterCase(str, true);
    }

    private static String changeFirstCharacterCase(String str, boolean capitalize) {
        if (str == null || str.length() == 0) {
            return str;
        } else {
            char baseChar = str.charAt(0);
            char updatedChar;
            if (capitalize) {
                updatedChar = Character.toUpperCase(baseChar);
            } else {
                updatedChar = Character.toLowerCase(baseChar);
            }
            if (baseChar == updatedChar) {
                return str;
            }
            char[] chars = str.toCharArray();
            chars[0] = updatedChar;
            return new String(chars, 0, chars.length);
        }
    }
}

Related

  1. capitalize(String str)
  2. capitalize(String str)
  3. capitalize(String str)
  4. capitalize(String str)
  5. capitalize(String str)
  6. capitalize(String str)
  7. capitalize(String str)
  8. capitalize(String str)
  9. capitalize(String str)