How to capitalize the first letter of a String in Java?

How to capitalize the first letter of a String in Java?

String str = java;
String cap = str.substring(0, 1).toUpperCase() + str.substring(1);
// cap = Java

With your example:

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    // Actually use the Reader
    String name = br.readLine();
    // Dont mistake String object with a Character object
    String s1 = name.substring(0, 1).toUpperCase();
    String nameCapitalized = s1 + name.substring(1);
    System.out.println(nameCapitalized);
}

StringUtils.capitalize(..) from commons-lang

How to capitalize the first letter of a String in Java?

The shorter/faster version code to capitalize the first letter of a String is:

String name  = stackoverflow; 
name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();

the value of name is Stackoverflow

Leave a Reply

Your email address will not be published.