Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
getlength
arrayutils
communitycreator

What is ArrayUtils.getLength in Java?

abhilash

getLength is a static method of the ArrayUtils class that returns the number of elements in the given array (i.e., the length of the given array).

This method can deal with both object type arrays as well as primitive type arrays.

Example 1

  • array = [1,2,3,4,5]

Applying the getLength function will result in 5 as the array’s length is 5.

Example 2

  • array = null

Applying the getLength function will result in 0 as the array passed is null.

ArrayUtils is defined in the Apache Commons Lang package. Apache Commons Lang can be added 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 ArrayUtils class as follows:

import org.apache.commons.lang3.ArrayUtils;

Syntax

public static int getLength(Object array)

Parameters

  • Object array - the array to find the length of.

Return value

The function returns the length of the array.

0 is returned if the array points to null.

IllegalArgumentException is returned if the passed argument is not an array.

Code

import org.apache.commons.lang3.ArrayUtils;

public class Main {

    public static void main(String[] args) {
        int[] array = {1,2,3,4,5};
        System.out.println(ArrayUtils.getLength(array));
        System.out.println(ArrayUtils.getLength(null));
        System.out.println(ArrayUtils.getLength("hello"));
    }
}

Expected output

5
0
Exception in thread "main" java.lang.IllegalArgumentException: Argument is not an array
	at java.base/java.lang.reflect.Array.getLength(Native Method)
	at org.apache.commons.lang3.ArrayUtils.getLength(ArrayUtils.java:1710)
	at Main.main(Main.java:9)

The code above throws an exception in the last statement of the main method, as the passed argument to the getLength method is not an array.

RELATED TAGS

java
getlength
arrayutils
communitycreator
RELATED COURSES

View all Courses

Keep Exploring