What is StringUtils.length in Java?

length() is a staticthe methods in Java that can be called without creating an object of the class. method of the StringUtils which is used to get the length of the character sequence. The method returns zero if the input character sequence/string is null.

How to import StringUtils

StringUtils is defined in the Apache Commons Lang package. We can add 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 int length(final CharSequence cs)

Parameters

final CharSequence cs: The character sequence/string.

Return value

This method returns the length of the character sequence/string.

Code

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

Example 1

  • string = "hellO-EDUcative"

The method returns 15 i.e., the number of characters in the input string.

Example 2

  • string = ""

The method returns 0 because the input string is empty.

Example 3

  • string = null

The method returns 0 because the input string is null.

Output

The output of the code will be as follows:


The output of StringUtils.length() for the string - 'hellO-EDUcative' is '15'
The output of StringUtils.length() for the string - '' is '0'
The output of StringUtils.length() for the string - 'null' is '0'
Attributions:
  1. undefined by undefined