How to capitalize the first letter of a String in Java
In Java, we can use substring(0, 1).toUpperCase() + str.substring(1)
to make the first letter of a String as a capital letter (uppercase letter)
2 3 4 5 6 7 8 |
String str = "tahasivaci"; String str1 = str.substring(0, 1).toUpperCase(); // first letter = T String str2 = str.substring(1); // after 1 letter = ahasivaci String result = str.substring(0, 1).toUpperCase() + str.substring(1); // T + ahasivaci |
substring(0,1).toUpperCase() + str.substring(1)
A complete Java example to capitalize the first letter of a String, and a null and length checking.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.tahasivaci.string; public class UppercaseFirstLetter { public static void main(String[] args) { System.out.println(capitalize("tahasivaci")); // Tahasivaci System.out.println(capitalize("a")); // A System.out.println(capitalize("@tahasivaci")); // @tahasivaci //String capitalize = StringUtils.capitalize(str); //System.out.println(capitalize); } // with some null and length checking public static final String capitalize(String str) { if (str == null || str.length() == 0) return str; return str.substring(0, 1).toUpperCase() + str.substring(1); } } |
Output
2 3 4 5 6 |
Tahasivaci A @tahasivaci |
References
Please don’t forget to leave a comment if you have any questions.
Recent Comments