Skip to content

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:


java
String s = "hello";

// Guard against null or empty strings
if (s != null && !s.isEmpty()) {
    // 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:


console
Original string: hello
Capitalized string: Hello

Alternatively, you can use Character.toUpperCase() for a more robust and standard approach that avoids regex pitfalls:


java
String s = "hello";

// Guard against null or empty strings
if (s != null && !s.isEmpty()) {
    // Capitalize the first letter
    String capitalized = Character.toUpperCase(s.charAt(0)) + s.substring(1);
    System.out.println("Original string: " + s);
    System.out.println("Capitalized string: " + capitalized);
}

I hope this helps! Let me know if you have any questions.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.