What is StringUtils.swapCase in Java?

swapCase() is a staticdescribes the methods in Java that can be called without creating an object of the class method of the StringUtils class that is used to swap the case of the characters according to the following rules:

  1. Upper case characters are converted to Lower case.

  2. Title case characters are converted to Lower case.

  3. Lower case characters are converted to Upper case.

How to import StringUtils

The definition of StringUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:


<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

For other versions of the commons-lang package, refer to the Maven Repository.

You can import the StringUtils class as follows.


import org.apache.commons.lang3.StringUtils;

Syntax


public static String swapCase(String str)

Parameters

String str: The string to change cases.

Return value

This method returns a new string.

Code

import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) {
// Example 1
String s = "heLlo-eDUcatIVe";
System.out.printf("The output of StringUtils.swapCase() for the string - '%s' is '%s'", s, StringUtils.swapCase(s));
System.out.println();
// Example 2
s = "";
System.out.printf("The output of StringUtils.swapCase() for the string - '%s' is '%s'", s, StringUtils.swapCase(s));
System.out.println();
// Example 3
s = null;
System.out.printf("The output of StringUtils.swapCase() for the string - '%s' is '%s'", s, StringUtils.swapCase(s));
System.out.println();
}
}

Example 1

  • string = "heLlo-eDUcatIVe"

The method returns HElLO-EduCATivE with the cases of the characters in the string swapped.

Example 2

  • strings = ""

The method returns `` because the string is empty.

Example 3

  • strings = null

The method returns null because the string is null.

Expected output

The output of the code is as follows:


The output of StringUtils.swapCase() for the string - 'heLlo-eDUcatIVe' is 'HElLO-EduCATivE'
The output of StringUtils.swapCase() for the string - '' is ''
The output of StringUtils.swapCase() for the string - 'null' is 'null'

Free Resources

Attributions:
  1. undefined by undefined