How to capitalize the first letter of a String in Java?
To capitalize the first letter of a string in Java, you can use the toUpperCase
method of the java.lang.String
class. Here's an example of how you can do this:
String s = "hello";
// Capitalize the first letter
String capitalized = s.substring(0, 1).toUpperCase() + s.substring(1);
System.out.println("Original string: " + s);
System.out.println("Capitalized string: " + capitalized);
This will output the following:
Original string: hello Capitalized string: Hello
Alternatively, you can use the charAt
and toUpperCase
methods to capitalize the first letter like this:
String s = "hello";
// Capitalize the first letter
String capitalized = s.replaceFirst(String.valueOf(s.charAt(0)), String.valueOf(s.charAt(0)).toUpperCase());
System.out.println("Original string: " + s);
System.out.println("Capitalized string: " + capitalized);
I hope this helps! Let me know if you have any questions.