ArrayUtils
About
ArrayUtils is a utility class provided by Apache Commons Lang to simplify working with Java arrays. Java arrays are low-level and have limited built-in methods, making operations like searching, copying, checking for emptiness, or merging somewhat cumbersome.
ArrayUtils provides null-safe, convenient, and readable methods to handle arrays of all primitive types and objects. It also helps avoid manual loops, System.arraycopy, and verbose boilerplate code.
Characteristics
All methods are static.
Handles both primitive and object arrays.
Offers null safety — no need to check for
nullbefore calling utility methods.Reduces common array operations to one-liners.
Maven Dependency & Import
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version> <!-- or latest -->
</dependency>import org.apache.commons.lang3.ArrayUtils;Common Categories of Methods
1. Null and Empty Checks
isEmpty(array)
Returns true if array is null or length is 0
isNotEmpty(array)
Returns true if array is not null and has elements
Example:
2. Array Creation and Conversion
toObject(int[])
Converts a primitive array to wrapper array
toPrimitive(Integer[])
Converts wrapper array to primitive array
nullToEmpty(array)
Converts null array to empty array
Example:
3. Element Checks
contains(array, value)
Checks if array contains a specific element
indexOf(array, value)
Returns the index of the element, or -1
lastIndexOf(array, value)
Returns the last index of the element
Example:
4. Adding and Removing Elements
add(array, value)
Adds value at the end
add(array, index, value)
Inserts value at a specific index
remove(array, index)
Removes value at index
removeElement(array, value)
Removes first occurrence of value
Example:
5. Concatenation and Cloning
addAll(array1, array2)
Concatenates arrays
clone(array)
Returns a clone of the array
subarray(array, startIndex, endIndex)
Gets a range of elements
Example:
6. Array Reversal and Shuffling
reverse(array)
Reverses the array in place
shuffle(array)
Randomizes the order (not in standard ArrayUtils, but can use custom logic)
Example:
7. Equality and Comparison
isSameLength(array1, array2)
Checks if two arrays are of the same length
isEquals(array1, array2)
Checks if all elements are equal
8. Array Type Checking
isArray(Object obj)
Checks whether a given object is an array
Why Use ArrayUtils Instead of Raw Java?
ArrayUtils Instead of Raw Java?Concern
Raw Java Approach
ArrayUtils Advantage
Null-safety
Manual checks
Built-in null checks
Adding/removing
Manual resizing or arraycopy
Simple one-liners
Searching
Manual loops
Ready-made methods
Conversion
Tedious type boxing/unboxing
Simplified conversions
Last updated