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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package com.javacodeexamples.stringexamples; public class StringInvertCharCaseExample { public static void main(String[] args) { String str = "JAVA string CASE iNvErT eXaMpLe 123."; //get char array from String char[] charArray = str.toCharArray(); //process chars one by one for(int i=0; i < charArray.length; i++){ //if char is uppercase, make it lower case if( Character.isUpperCase(charArray[i]) ){ charArray[i] = Character.toLowerCase( charArray[i] ); }else if(Character.isLowerCase(charArray[i]) ){ charArray[i] = Character.toUpperCase( charArray[i] ); } } //convert modified char array back to String str = new String(charArray); System.out.println(str); } } |
Output
1 |
java STRING case InVeRt ExAmPlE 123. |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.javacodeexamples.stringexamples; import org.apache.commons.lang3.StringUtils; public class StringInvertCharCaseExample { public static void main(String[] args) { String str = "JAVA string CASE iNvErT eXaMpLe 123."; System.out.println( StringUtils.swapCase(str) ); } } |
Output
1 |
java STRING case InVeRt ExAmPlE 123. |
This example is a part of the Java String tutorial with examples.
Please let me know your views in the comments section below.