How to invert the case of a String in Java

In this post, we will see how to invert the case of a String in Java. The solution should convert each Upper case character present in the string to lower case and each lower case character to Upper case.


1. Naive

We know that String class in Java didn’t provide anything built-in to invert the case of a String. However we can write our custom routine for this easy task. The idea is to iterate through the String and invert case of each encountered character. Since String is immutable, we can convert the String to a character array as shown below:


Download   Run Code


iNVERT mY case


2. Apache Commons

We can also leverage Apache Commons library which has a swapCase() method present in StringUtils class.


Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of