This post will discuss 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 lower case characters to the upper case.

1. Naive method

We know that the 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 the case of each encountered character. Since the string is immutable, we can convert the string to a character array, as shown below:

Download  Run Code

Output:

iNVERT mY case

2. Using Apache Commons Lang

We can also leverage the Apache Commons Lang library, the swapCase() method present in the StringUtils class.

Download Code

That’s all about inverting the case of a Java String.