Java String Handling

Invert case of String in Java example

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

How to invert 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 Character class

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


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

2) Invert case of String using Apache Commons Library

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


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


Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.