Introduction

Converting a string to upper case is a common requirement in Java programming. Whether you are dealing with user input or manipulating text data, it’s important to know how to transform strings to a consistent case format. In this tutorial, we will explore different approaches to convert a string to upper case in Java.

Using the toUpperCase() Method

The easiest way to convert a string to upper case in Java is by using the toUpperCase() method provided by the String class. This method converts all characters in the string to their uppercase equivalents. Here’s an example:

String str = ""hello, world!"";
String upperCaseStr = str.toUpperCase();
System.out.println(upperCaseStr);

Output:

HELLO, WORLD!

In the above code, the toUpperCase() method is called on the string str and the result is assigned to the upperCaseStr variable. The System.out.println() statement displays the converted string.

Using the String.toUpperCase(Locale) Method

The toUpperCase() method also has an overloaded version that accepts a Locale parameter. This allows you to control how the conversion is done based on the specified locale’s rules. For example, in some languages, converting the letter ‘i’ to uppercase might produce a different result.

String str = ""café"";
String upperCaseStr = str.toUpperCase(Locale.FRENCH);
System.out.println(upperCaseStr);

Output:

CAFÉ

In the above code, the toUpperCase(Locale.FRENCH) method is called to convert the string str to uppercase based on the French locale. Notice that the ‘é’ character remains unchanged as per the French language rules.

Using Custom Implementation

If you prefer a custom implementation to convert a string to upper case, you can iterate over the characters of the string and manually convert each character to its uppercase equivalent. Here’s an example:

String str = ""hello, world!"";
StringBuilder stringBuilder = new StringBuilder();

for (char c : str.toCharArray()) {
    if (Character.isLetter(c)) {
        stringBuilder.append(Character.toUpperCase(c));
    } else {
        stringBuilder.append(c);
    }
}

String upperCaseStr = stringBuilder.toString();
System.out.println(upperCaseStr);

Output:

HELLO, WORLD!

In the above code, we iterate over each character of the string str. If the character is a letter, we convert it to uppercase using Character.toUpperCase() and append it to the stringBuilder. If it’s not a letter, we append it as it is. Finally, we convert the stringBuilder to a string using toString() method and display the result.

Conclusion

Converting a string to upper case in Java is straightforward using the built-in toUpperCase() method. Additionally, the overloaded version of toUpperCase() with the Locale parameter allows you to handle case conversion based on specific language rules. If you need more customization, you can implement a custom solution by iterating over the characters of the string.

I hope you found this tutorial helpful!