reverse()
is a StringUtils
class, used to reverse a given string.
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;
The syntax of the reverse()
method is as follows:
public static String reverse(final String str)
The reverse()
method takes the following parameter:
final String str
: The string to reverse.This method returns the reversed string.
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 1String 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 2s = "";System.out.printf("The output of StringUtils.reverse() for the string - '%s' is '%s'", s, StringUtils.reverse(s));System.out.println();// Example 3s = null;System.out.printf("The output of StringUtils.reverse() for the string - '%s' is '%s'", s, StringUtils.reverse(s));System.out.println();}}
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'
string = "hellO-EDUcativeaa"
The method returns aaevitacUDE-Olleh
,i.e., the reversed string.
string = ""
The method returns `` as the input string is empty.
string = null
The method returns null
as the input string is null
.