length()
is a StringUtils
which is used to get the length of the character sequence. The method returns zero if the input character sequence/string is null
.
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;
public static int length(final CharSequence cs)
final CharSequence cs
: The character sequence/string.
This method returns the length of the character sequence/string.
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();}}
string = "hellO-EDUcative"
The method returns 15
i.e., the number of characters in the input string.
string = ""
The method returns 0
because the input string is empty.
string = null
The method returns 0
because the input string is null
.
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'