Capitalize the First Letter of a String in Java Example

Let's write a Java program to uppercase or capitalize the first character of given String in Java.

Capitalize the First Letter of a String in Java Example

package net.javaguides.corejava.string;

public class UppercaseFirstChar {
    /**
     * Returns the input argument, but ensures the first character is
     * capitalized (if possible).
     * 
     * @param in
     *            the string to uppercase the first character.
     * @return the input argument, but with the first character capitalized (if
     *         possible).
     * @since 1.2
     */
    public static String uppercaseFirstChar(String in ) {
        if ( in == null || in .length() == 0) {
            return in;
        }
        int length = in .length();
        StringBuilder sb = new StringBuilder(length);

        sb.append(Character.toUpperCase( in .charAt(0)));
        if (length > 1) {
            String remaining = in .substring(1);
            sb.append(remaining);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String output = UppercaseFirstChar.uppercaseFirstChar("java");
        String output1 = UppercaseFirstChar.uppercaseFirstChar("source");
        String output2 = UppercaseFirstChar.uppercaseFirstChar("code");
        String output3 = UppercaseFirstChar.uppercaseFirstChar("examples");
        System.out.println(" Output string -> " + output);
        System.out.println(" Output string -> " + output1);
        System.out.println(" Output string -> " + output2);
        System.out.println(" Output string -> " + output3);

    }
}
Output:
 Output string -> Java
 Output string -> Source
 Output string -> Code
 Output string -> Examples

Reference


Comments