Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
wordutils
swapcase
communitycreator

What is WordUtils.swapCase in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

swapCase is a static method of the WordUtils class that is used to swap the case of a string using a word-based algorithm.

  • Uppercase and title case characters are converted to lowercase.
  • Lowercase characters after whitespace or at the start get converted to title case.
  • Other lowercase characters get converted to uppercase.

WordUtils is defined in the Apache Commons Text package. Apache Commons Text can be added to the Maven project by adding the following dependency to the pom.xml file.

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

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

You can import the WordUtils class as follows:

import org.apache.commons.text.WordUtils;

Syntax

public static String swapCase(final String str)

Parameters

  • final String str: string to swap case

Returns

This method returns a new character case-swapped string.

Code

import org.apache.commons.text.WordUtils;

public class Main {

    public static void main(String[] args) {
        String text = "HelLO eDucAtiVe";
        String swapCase = WordUtils.swapCase(text);
        System.out.println("text after case swap - " + swapCase);
    }
}

Example

  • text = "HelLO eDucAtiVe"

Applying the swapCase method would result in hELlo EdUCaTIvE. The case of each letter is swapped with lower or uppercase, respectively.

Expected output

text after case swap - hELlo EdUCaTIvE

RELATED TAGS

java
wordutils
swapcase
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring