How to Capitalize Strings in Java

Introduction

Capitalizing strings in Java can refer to converting the first letter of a string or each word in a string to uppercase while keeping the rest of the letters in lowercase. This operation is commonly required in formatting text, such as titles or names. In this blog post, we will explore different methods to capitalize strings in Java.

Table of Contents

  1. Capitalizing the First Letter of a String
    • Using substring() and toUpperCase()
    • Using StringBuilder
    • Using Apache Commons Lang WordUtils
  2. Capitalizing the First Letter of Each Word in a String
    • Using String.split()
    • Using Streams (Java 8+)
    • Using Apache Commons Lang WordUtils
  3. Complete Example Program
  4. Conclusion

1. Capitalizing the First Letter of a String

Using substring() and toUpperCase()

This method involves converting the first character to uppercase and concatenating it with the rest of the string in lowercase.

Example:

public class CapitalizeFirstLetter {
    public static void main(String[] args) {
        String str = "hello world";

        if (str == null || str.isEmpty()) {
            System.out.println("String is empty or null");
        } else {
            String capitalizedStr = str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
            System.out.println("Capitalized String: " + capitalizedStr);
        }
    }
}

Using StringBuilder

The StringBuilder class can also be used to achieve this by directly modifying the characters.

Example:

public class CapitalizeFirstLetterUsingStringBuilder {
    public static void main(String[] args) {
        String str = "hello world";

        if (str == null || str.isEmpty()) {
            System.out.println("String is empty or null");
        } else {
            StringBuilder sb = new StringBuilder(str);
            sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
            String capitalizedStr = sb.toString();
            System.out.println("Capitalized String: " + capitalizedStr);
        }
    }
}

Using Apache Commons Lang WordUtils

Apache Commons Lang library provides a utility class WordUtils which can be used to capitalize the first letter of a string.

Maven Dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Example:

import org.apache.commons.lang3.text.WordUtils;

public class CapitalizeFirstLetterUsingWordUtils {
    public static void main(String[] args) {
        String str = "hello world";

        String capitalizedStr = WordUtils.capitalize(str);
        System.out.println("Capitalized String: " + capitalizedStr);
    }
}

2. Capitalizing the First Letter of Each Word in a String

Using String.split()

This method involves splitting the string into words, capitalizing each word, and then joining them back together.

Example:

public class CapitalizeEachWord {
    public static void main(String[] args) {
        String str = "hello world from java";

        if (str == null || str.isEmpty()) {
            System.out.println("String is empty or null");
        } else {
            String[] words = str.split("\\s+");
            StringBuilder capitalizedStr = new StringBuilder();

            for (String word : words) {
                if (!word.isEmpty()) {
                    capitalizedStr.append(Character.toUpperCase(word.charAt(0)))
                                  .append(word.substring(1).toLowerCase())
                                  .append(" ");
                }
            }

            System.out.println("Capitalized String: " + capitalizedStr.toString().trim());
        }
    }
}

Using Streams (Java 8+)

The Stream API provides a concise way to capitalize each word in a string.

Example:

import java.util.Arrays;
import java.util.stream.Collectors;

public class CapitalizeEachWordUsingStreams {
    public static void main(String[] args) {
        String str = "hello world from java";

        if (str == null || str.isEmpty()) {
            System.out.println("String is empty or null");
        } else {
            String capitalizedStr = Arrays.stream(str.split("\\s+"))
                                          .map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1).toLowerCase())
                                          .collect(Collectors.joining(" "));

            System.out.println("Capitalized String: " + capitalizedStr);
        }
    }
}

Using Apache Commons Lang WordUtils

The WordUtils class can also be used to capitalize the first letter of each word in a string.

Example:

import org.apache.commons.lang3.text.WordUtils;

public class CapitalizeEachWordUsingWordUtils {
    public static void main(String[] args) {
        String str = "hello world from java";

        String capitalizedStr = WordUtils.capitalizeFully(str);
        System.out.println("Capitalized String: " + capitalizedStr);
    }
}

3. Complete Example Program

Here is a complete program that demonstrates the methods discussed above to capitalize the first letter of each word and the first letter of a string in Java.

Example Code:

import org.apache.commons.lang3.text.WordUtils;
import java.util.Arrays;
import java.util.stream.Collectors;

public class CapitalizeStringExample {
    public static void main(String[] args) {
        String str1 = "hello world";
        String str2 = "hello world from java";

        // Capitalize first letter of a string using substring and toUpperCase
        if (str1 != null && !str1.isEmpty()) {
            String capitalizedStr1 = str1.substring(0, 1).toUpperCase() + str1.substring(1).toLowerCase();
            System.out.println("Using substring and toUpperCase: " + capitalizedStr1);
        }

        // Capitalize first letter of a string using StringBuilder
        if (str1 != null && !str1.isEmpty()) {
            StringBuilder sb1 = new StringBuilder(str1);
            sb1.setCharAt(0, Character.toUpperCase(sb1.charAt(0)));
            String capitalizedStr2 = sb1.toString();
            System.out.println("Using StringBuilder: " + capitalizedStr2);
        }

        // Capitalize first letter of each word using split and join
        if (str2 != null && !str2.isEmpty()) {
            String[] words = str2.split("\\s+");
            StringBuilder capitalizedStr3 = new StringBuilder();
            for (String word : words) {
                if (!word.isEmpty()) {
                    capitalizedStr3.append(Character.toUpperCase(word.charAt(0)))
                                   .append(word.substring(1).toLowerCase())
                                   .append(" ");
                }
            }
            System.out.println("Using split and join: " + capitalizedStr3.toString().trim());
        }

        // Capitalize first letter of each word using Streams
        if (str2 != null && !str2.isEmpty()) {
            String capitalizedStr4 = Arrays.stream(str2.split("\\s+"))
                                           .map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1).toLowerCase())
                                           .collect(Collectors.joining(" "));
            System.out.println("Using Streams: " + capitalizedStr4);
        }

        // Capitalize first letter of each word using WordUtils
        String capitalizedStr5 = WordUtils.capitalizeFully(str2);
        System.out.println("Using WordUtils.capitalizeFully: " + capitalizedStr5);
    }
}

Output:

Using substring and toUpperCase: Hello world
Using StringBuilder: Hello world
Using split and join: Hello World From Java
Using Streams: Hello World From Java
Using WordUtils.capitalizeFully: Hello World From Java

4. Conclusion

Capitalizing strings in Java can be done in various ways. For capitalizing the first letter of a string, you can use substring() with toUpperCase() or StringBuilder. For capitalizing the first letter of each word in a string, you can use split() with a loop, the Stream API, or the WordUtils class from Apache Commons Lang. Each method has its own advantages and use cases, so you can choose the one that best fits your needs and coding style.

Happy coding!

Comments