Swap Lowercase and Uppercase of a String in Java using Apache Commons Text

Tags: Apache Commons Apache Commons Text WordUtils String

Introduction

In this article we are going to learn how to swap the case of a String in Java application. We provide a Java code example to show how to use WordUtils.swapCase() method of Apache Commons Text library to swap the case of each character of a given String.

Setup Apache Commons Text in Java project

If you are using Gradle build then add the following dependency configuration into build.gradle file.

compile group: 'org.apache.commons', name: 'commons-text', version: '1.9'

Or add the following dependency XML tag to pom.xml file if you are using Maven build.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.9</version>
</dependency>

Or download commons-text-1.9.jar file from Apache Commons Text download page at commons.apache.org

Java code example how to use org.apache.commons.text.WordUtils.swapCase()

import org.apache.commons.text.WordUtils;

public class WordUtilsSwapCaseExample {
    public static void main(String[] args) {
        String result1 = WordUtils.swapCase("This is a STRING to tEST");
        String result2 = WordUtils.swapCase("this is a string");
        String result3 = WordUtils.swapCase("THIS IS A STRING");
        String result4 = WordUtils.swapCase("This Is A String");

        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
        System.out.println(result4);
    }
}
Output:

tHIS IS A string TO Test
THIS IS A STRING
this is a string
tHIS iS a sTRING

Happy Coding 😊