Java String Capitalize

1. Introduction

Capitalizing the first letter of a string in Java is a common task in text processing and formatting. While Java's standard library does not provide a direct method to capitalize strings, this operation can be easily achieved through simple string manipulation techniques. This blog post will demonstrate how to capitalize the first letter of a string in Java, an essential skill for formatting user inputs, displaying data with consistent styling, or preparing text for processing.

2. Program Steps

1. Check if the input string is null or empty to handle edge cases.

2. Extract the first character of the string.

3. Convert the first character to uppercase.

4. Concatenate the uppercase first character with the rest of the string.

5. Display the capitalized string.

3. Code Program

public class StringCapitalizeExample {
    public static void main(String[] args) {
        String inputString = "java programming"; // Input string to be capitalized
        String capitalizedString = capitalizeFirstLetter(inputString); // Capitalizing the first letter

        System.out.println("Original String: " + inputString);
        System.out.println("Capitalized String: " + capitalizedString);
    }

    // Method to capitalize the first letter of a string
    public static String capitalizeFirstLetter(String str) {
        // Step 1: Check if the string is null or empty
        if (str == null || str.isEmpty()) {
            return str;
        }

        // Step 2 & 3: Extract the first character and convert to uppercase
        String firstLetter = str.substring(0, 1).toUpperCase();

        // Step 4: Concatenate the uppercase first character with the rest of the string
        return firstLetter + str.substring(1);
    }
}

Output:

Original String: java programming
Capitalized String: Java programming

Explanation:

1. The program begins with an input string inputString, set to "java programming". The goal is to capitalize the first letter of this string.

2. The capitalizeFirstLetter method is designed to perform the capitalization. It first checks if the input string is null or empty to avoid NullPointerException or to handle strings that don't need modification.

3. It then extracts the first character of the string with str.substring(0, 1) and converts this character to uppercase using toUpperCase().

4. The method concatenates the uppercase first character with the remainder of the original string, obtained by str.substring(1). This effectively replaces the first character with its uppercase variant while leaving the rest of the string unchanged.

5. The main method displays both the original and the capitalized strings, demonstrating the effect of the capitalizeFirstLetter method. The output shows that the first letter of the input string has been successfully converted to uppercase, illustrating a simple yet effective approach to capitalizing the first letter of a string in Java.

Comments