How to capitalize the first letter of a string in Java

The first letter of a string can be capitalized using the following methods.

Capitalize the first letter of string using the toUpperCase() method

The first letter of the string is capitalized using toUpperCase() and substring() methods.

String str = "";
String word = "multipurpose";
str += Character.toUpperCase(word.charAt(0)) + word.substring(1) + " ";
System.out.println(str.trim());

The output is

Multipurpose

Capitalize the first letter of string using the ASCII values

The first letter of the string is checked using the if condition, if it is in lowercase it is converted to uppercase by adding the respective ASCII values.

String str = "happiness";
char ch[] = str.toCharArray();
for (int i = 0; i < str.length(); i++) {
  if (i == 0 && ch[i] != ' ' ||
    ch[i] != ' ' && ch[i - 1] == ' ') {
    if (ch[i] >= 'a' && ch[i] <= 'z') {
      ch[i] = (char)(ch[i] - 'a' + 'A');
    }
  } else if (ch[i] >= 'A' && ch[i] <= 'Z')
    ch[i] = (char)(ch[i] + 'a' - 'A');
}
String s = new String(ch);
System.out.println(s);

The output is

Happiness
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions