What is StringUtils.right() in Java?

Overview

right() is a staticthe methods in Java that can be called without creating an object of the class. method of the StringUtils class that is used to get the rightmost characters of a 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


public static String right(final String str, final int len)

Parameters

  • final String str: The string to get the rightmost characters from.
  • final int len: The length of the rightmost characters to extract from the string.

Return value

This method returns the rightmost characters of the string.

Code

The code below shows how the right() method works in Java.

import org.apache.commons.lang3.StringUtils;
public class Main{
public static void main(String[] args) {
// Example 1
String string = "hello-educative";
int len = 5;
System.out.printf("StringUtils.right('%s', %s) = '%s'", string, len, StringUtils.right(string, len));
System.out.println();
// Example 2
len = -1;
System.out.printf("StringUtils.right('%s', %s) = '%s'", string, len, StringUtils.right(string, len));
System.out.println();
}
}

Output

The output of the code will be as follows:


StringUtils.right('hello-educative', 5) = 'ative'
StringUtils.right('hello-educative', -1) = ''

Explanation

Example 1

  • string = "hello-educative"
  • length = 5

The method returns ative which is the rightmost substring of the given string with length 5.

Example 2

  • string = "hello-educative"
  • length = -1

The method returns ``, an empty string, as the length value is negative.

Free Resources

Attributions:
  1. undefined by undefined
  2. undefined by undefined