What is StringUtils.left() in Java?

left() is a staticthe methods in Java that can be called without creating an object of the class method of the StringUtils class which is used to get the specified number of leftmost 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 left(String str, int len)

Parameters

  • str: The string to get the leftmost characters from.
  • len: The length of the leftmost characters to extract from the string.

Return value

  • This method returns the leftmost characters of the string.

  • If len is negative, then an empty string is returned.

  • If str is null or the value of len is not available, then an empty string is returned.

Code

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

Output

The output of the code is as follows:


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

Explanation

Example 1

  • str = "hello-educative"
  • len = 5

The method returns "hello" which is the leftmost substring of the given string with length 5.

Example 2

  • str = "hello-educative"
  • len = -1

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

Free Resources

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