Explain Codes LogoExplain Codes Logo

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

java
prompt-engineering
functions
best-practices
Anton ShumikhinbyAnton Shumikhin·Feb 15, 2025
TLDR

Here's the way to capitalize the first letter of a String in Java:

String capitalized = Character.toUpperCase(input.charAt(0)) + input.substring(1);

This method assumes our input String is not empty and takes the first character to uppercase, appending the rest unmodified.

Delving into Java Strings and Characters

In Java, understanding the difference between String and Character is crucial. A String is an object that represents a sequence of characters, whereas Character is a wrapper class for the primitive data type char.

When it comes to capitalization, we might be tempted to call toUpperCase() on a char. However, this will lead to compilation errors because this method is only applicable to String objects. Yes, Java can be really picky!

Processing user input

For user input, we often pair BufferedReader with InputStreamReader. They're like a dynamic programming duo, with BufferedReader handling buffering to provide efficient reading of texts:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String input = reader.readLine();

However, with great power comes great responsibility! We have to deal with the IOException that readLine() may throw. To handle this, we wrap our code in a try-catch block:

try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { String input = reader.readLine(); // All hail the capitalized string! } catch (IOException e) { System.out.println("Something went wrong. It's not you, it's me!"); }

Deploying the power of libraries

To capitalize a String, you can employ the power of Apache's StringUtils:

import org.apache.commons.lang3.StringUtils; String capitalized = StringUtils.capitalize(input.toLowerCase());

To utilize this helper method, you need to bring in the commons-lang3 dependency in your Gradle build:

implementation 'org.apache.commons:commons-lang3:3.12.0'

If you have a Spring-oriented project, it makes sense to use Spring's StringUtils. Your project will thank you for being consistent!

Edge Cases and Input Validation

Working with Strings is not always straightforward. We must consider some edge cases:

  1. Empty Strings: Always check if the string is empty to prevent a StringIndexOutOfBoundsException.
  2. Single Characters: If all we have is a single character, there's no point in using substring functions. A simple charToUpperCase() would suffice.
  3. Unicode Inputs: Ensure your method supports Unicode characters. Dropping characters is not in good taste!
  4. Locale-Specific Rules: Sometimes, capitalization rules change based on language/locale. In these situations, use toUpperCase(Locale locale) to avoid international faux pas.

Best practices for error elimination

A few tips to avoid problems in your code:

  • Remember the first rule of String Club: Always validate the input for null or empty values. This prevents unwanted NullPointerExceptions.
  • Don't reinvent the wheel: consider using well-tested libraries such as Apache Commons StringUtils or Google Guava.
  • Refrain from deprecated methods like WordUtils.capitalize. Your future self will thank you for not using deprecated stuff.

Alternative methods

Looking for a bit of diversity? Consider these alternatives:

  • Embrace the power of helpers: you can build your capitalization function, utilizing Java's Character class's methods to do the heavy lifting.
  • Go flow with streams: Some transformations might require going beyond capitalizing; this is the time streams can prove to be helpful.