What is StringUtils.reverse() in Java?

Overview

reverse() is a staticthe methods in Java that can be called without creating an object of the class. method of the StringUtils class, used to reverse a given string.

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

The syntax of the reverse() method is as follows:


public static String reverse(final String str)

Parameters

The reverse() method takes the following parameter:

  • final String str: The string to reverse.

Return value

This method returns the reversed string.

Code

The code below shows how the reverse() method works in Java:

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

Output

The output of the code will be as follows:


The output of StringUtils.reverse() for the string - 'hellO-EDUcativeaa' is 'aaevitacUDE-Olleh'
The output of StringUtils.reverse() for the string - '' is ''
The output of StringUtils.reverse() for the string - 'null' is 'null'

Explanation

Example 1

  • string = "hellO-EDUcativeaa"

The method returns aaevitacUDE-Olleh,i.e., the reversed string.

Example 2

  • string = ""

The method returns `` as the input string is empty.

Example 3

  • string = null

The method returns null as the input string is null.

Attributions:
  1. undefined by undefined