swapCase() is a StringUtils class that is used to swap the case of the characters according to the following rules:
Upper case characters are converted to Lower case.
Title case characters are converted to Lower case.
Lower case characters are converted to Upper case.
StringUtilsThe 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-langpackage, refer to the Maven Repository.
You can import the StringUtils class as follows.
import org.apache.commons.lang3.StringUtils;
public static String swapCase(String str)
String str: The string to change cases.
This method returns a new string.
import org.apache.commons.lang3.StringUtils;public class Main {public static void main(String[] args) {// Example 1String 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 2s = "";System.out.printf("The output of StringUtils.swapCase() for the string - '%s' is '%s'", s, StringUtils.swapCase(s));System.out.println();// Example 3s = null;System.out.printf("The output of StringUtils.swapCase() for the string - '%s' is '%s'", s, StringUtils.swapCase(s));System.out.println();}}
string = "heLlo-eDUcatIVe"The method returns HElLO-EduCATivE with the cases of the characters in the string swapped.
strings = ""The method returns `` because the string is empty.
strings = nullThe method returns null because the string is null.
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