Capitalize String for the first letter - Java java.lang

Java examples for java.lang:String Capitalize

Description

Capitalize String for the first letter

Demo Code

public class Main {

  public static void main(String[] argv) {
    String string = "java2s.com";
    System.out.println(capitalizedString(string));
    //w  ww  . java2 s. c o m
    string = "this is a test";
    System.out.println(capitalizedString(string));
  }

  public static String capitalizedString(String string) {
    if (string == null)
      return null;
    String capitalizedString = string;
    int length = capitalizedString.length();
    if (length > 0) {
      char character = capitalizedString.charAt(0);
      if (!(Character.isUpperCase(character))) {
        StringBuilder buffer = new StringBuilder(length);
        buffer.append(Character.toUpperCase(character));
        if (length > 1)
          buffer.append(capitalizedString.substring(1));

        capitalizedString = new String(buffer);
      }
    }
    return capitalizedString;
  }

}

Related Tutorials