Java - Write code to Capitalize the first letter.

Requirements

Write code to Capitalize the first letter.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String string = "book2s.com";
        System.out.println(capitalsFirst(string));
    }/*from ww w.jav  a  2 s  .  c  o  m*/

    private static final String TOLOWER = "lower";
    private static final String TOUPPER = "upper";

    /**
     * Capitalize the first letter.
     *
     * @param string the string to be capitalized first letter
     * @return
     */
    public static String capitalsFirst(final String string) {
        return capitalsFirstOrUn(TOUPPER, string);
    }

    /**
     * Capitalize or un-Capitalize the first letter
     *
     * @param type "lower" --> Capptalize; "upper" --> un-Capitalize
     * @param string the string to be capitalized or un-capitalized  first letter
     * @return
     */
    private static String capitalsFirstOrUn(final String type,
            final String string) {
        if (string == null) {
            return null;
        }

        if (string.length() == 0) {
            return "";
        }

        StringBuffer sb = new StringBuffer();
        if (TOLOWER.equals(type)) {
            sb.append(string.substring(0, 1).toLowerCase());
        } else if (TOUPPER.equals(type)) {
            sb.append(string.substring(0, 1).toUpperCase());
        }

        if (string.length() > 1) {
            sb.append(string.substring(1));
        }

        return sb.toString();
    }
}