Skip to content

Invert case of String in Java example

This Java example shows how to invert case of string in Java. The example also shows how to convert all uppercase letters to lowercase and all lowercase letters to uppercase or toggle case of string in Java using Apache Commons library.

How to invert the case of string in Java?

We want to make all uppercase letters of string to lowercase and all lowercase letters to uppercase. There are a couple of ways to do that as given below.

1) Invert case of String using the Character class

You can use the isUpperCase and isLowerCase methods of the Character class to check if a particular character is uppercase or lowercase. The toUpperCase or toLowerCase methods are used to change the case of a character. Here is the example program to do it.

Output

Basically, first of all, we took a character array from a string. For each character, we checked if it is an uppercase or lowercase character. If it was uppercase, we made it lowercase using the toLowerCase method and if it was lowercase we made it uppercase using the toUpperCase method. In the end, we converted the character array back to the string.

2) Using the Apache Commons Library

If you are using the Apache Commons library in your project, you can use the swapCase method of the StringUtils class to swap the case of a string as given below.

Output

This example is a part of the Java String tutorial with examples.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.