1. Introduction to the Arrays Class
Java provides the Arrays utility class in the java.util package. It contains useful static methods for performing common operations on arrays, including sorting, searching, copying, filling, and comparing.
Premium Video
This video is available to Premium members or users who have purchased the course.
Sign in to UnlockTo use these methods, import the class:
Because the methods are static, you call them using the class name, such as Arrays.sort(numbers), rather than creating an Arrays object.
Learning objectives
After reading this article, you will be able to:
- Import and use the
java.util.Arraysclass. - Print an array using
Arrays.toString(). - Sort values with
Arrays.sort(). - Search a sorted array with
Arrays.binarySearch(). - Fill and copy arrays.
- Compare arrays with
Arrays.equals()andArrays.compare(). - Recognize common mistakes when using these methods.
2. Arrays.toString()
The Arrays.toString() method returns a readable string representation of a one-dimensional array. It is convenient when you want to print all array elements rather than the array object's default reference-style representation.
Complete runnable example
Expected output
[10, 20, 30, 40, 50] How it works
Arrays.toString(numbers)creates a string containing the elements in order.System.out.println()prints that string.- For a two-dimensional or higher-dimensional array, use
Arrays.deepToString()when you want a nested representation of the contents.
3. Arrays.sort()
The Arrays.sort() method sorts array elements into ascending order for common primitive arrays such as int[], and sorts object arrays according to their natural ordering unless a comparator is supplied.
Complete runnable example
Expected output
[10, 20, 30, 40, 50]How it works
- The original array starts in the order
{50, 20, 40, 10, 30}. Arrays.sort(numbers)rearranges the elements in the same array.Arrays.toString(numbers)prints the sorted values.
Important: Arrays.sort() modifies the array passed to it. If you need to keep the original order, copy the array first with Arrays.copyOf().
4. Arrays.binarySearch()
The Arrays.binarySearch() method searches for a value in an array. For the result to be meaningful, the array should be sorted according to the ordering used by the search.
If the value is found, the method returns an index where the value occurs. If it is not found, it returns a negative value that encodes an insertion point; beginners should not assume every negative result means a particular fixed index.
Complete runnable example
Expected output
Index of 30: 2The value 30 is found at index 2.
Important: Sort the array before searching if it is not already sorted. If duplicate values exist, the method does not promise which matching index will be returned.
5. Arrays.fill()
The Arrays.fill() method assigns the same value to every element of an array. It is useful when you want to initialize or reset an array to one repeated value.
Complete runnable example
Expected output
[10, 10, 10, 10, 10]Filling a range
Arrays.fill(array, fromIndex, toIndex, value) fills the range starting at fromIndex and ending just before toIndex.
Expected output
[1, 9, 9, 9, 5]The start index is included, while the end index is excluded.
6. Arrays.copyOf()
The Arrays.copyOf() method creates a new array containing elements copied from the original array, up to the requested length.
Complete runnable example
Expected output
Original: [10, 20, 30]Copy: [10, 20, 30]
The returned array is a separate array object. For primitive arrays, the values are copied. For object arrays, the references are copied, not the referenced objects themselves.
Copying to a different length
If the requested length is greater than the original length, the new positions contain the type's default value. For an int[], that value is 0.
Expected output
[10, 20, 30, 0, 0]7. Arrays.equals()
The Arrays.equals() method checks whether two arrays contain equal elements in the same order. For primitive arrays, it compares corresponding primitive values. For object arrays, it compares corresponding elements using their equality behavior.
Complete runnable example
Expected output
true
false
a and b contain the same values in the same order, so the result is true. The elements in c are in a different order, so the result is false.
Note: a == b checks whether the two variables refer to the same array object; it does not compare their contents.
8. Arrays.compare()
Arrays.compare() lexicographically compares two arrays. It compares corresponding elements from left to right until it finds a difference. If all shared positions match, the shorter array is considered smaller.
- A negative result means the first array is lexicographically less than the second.
- Zero means the arrays compare as equal.
- A positive result means the first array is lexicographically greater than the second.
Complete runnable example
Expected output
true0
The first comparison is negative because 30 is less than 40 at the first differing position. The second comparison returns 0 because the arrays compare equally.
Java version note: Arrays.compare() was added in Java 9. If your platform uses Java 8, this method may not be available. Arrays.equals() is the simpler choice when you only need to test whether arrays contain the same elements in the same order.
9. Common Arrays Methods at a Glance
| Method | Purpose | Important note |
|---|---|---|
Arrays.toString(array) | Returns a readable string for a 1D array | Use deepToString() for nested arrays |
Arrays.sort(array) | Sorts an array | Modifies the supplied array |
Arrays.binarySearch(array, key) | Searches for a key | Use a correctly sorted array |
Arrays.fill(array, value) | Assigns one value to all elements | Range overload uses an exclusive end index |
Arrays.copyOf(array, length) | Creates a new array of the requested length | Longer copies get default values in new positions |
Arrays.equals(a, b) | Checks content equality in order | Does not mean the references are identical |
Arrays.compare(a, b) | Compares arrays lexicographically | Available from Java 9 |
10. Flowchart: Sort an Array and Search for a Value
This flowchart shows a common sequence: sort the array, perform binary search, and then display the result.
Flowchart explanation:
- Create or receive an integer array.
- Sort the array so binary search can be used correctly.
- Call
Arrays.binarySearch()with the target value. - If the returned index is zero or greater, the value was found.
- If the returned index is negative, the value was not found.
- Display the result and end.
11. Complete Example Using Multiple Methods
The following program demonstrates printing, sorting, and searching in one runnable example.
Expected output
Original: [50, 20, 40, 10, 30]
Sorted: [10, 20, 30, 40, 50]
Index of 30: 2
How it works
Arrays.toString()displays the initial order.Arrays.sort()sorts the original array in ascending order.Arrays.binarySearch()searches the sorted array.- The
ifstatement checks whether the result is non-negative before displaying the index.
12. Common Mistakes and Best Practices
Mistake 1: Calling binarySearch() on an unsorted array
Binary search relies on sorted order. Sort the array first if needed:
Mistake 2: Assuming sort() creates a new array
Arrays.sort(numbers) changes the supplied array. Use Arrays.copyOf() first if you need to preserve the original order.
Mistake 3: Printing an array directly
System.out.println(numbers) does not print the elements as a list. Use:
Mistake 4: Comparing array references instead of contents
Use Arrays.equals(a, b) to compare contents. The expression a == b checks whether both variables refer to the same array object.
Mistake 5: Misreading a negative binary-search result
A negative result means the key was not found. The exact negative value encodes an insertion point; do not treat it as a valid array index.
Best practices
- Import
java.util.Arrayswhen using these methods. - Read the method's behavior before using it: some methods modify the array, while others return a result or a new array.
- Sort before calling
binarySearch(). - Use
Arrays.toString()for one-dimensional arrays andArrays.deepToString()for nested arrays. - Check a
binarySearch()result before using it as an index. - Check your Java version before using
Arrays.compare().
13. Practice Questions with Answers
Question 1: Which package contains the Arrays class?
Answer: java.util.
Question 2: What does Arrays.toString() do?
Answer: It returns a readable string representation of a one-dimensional array.
Question 3: What is printed by this program?
Answer:
[1, 2, 3]Question 4: Why should an array be sorted before using Arrays.binarySearch()?
Answer: Binary search expects the array to be ordered according to the search's ordering. Searching an unsorted array can produce an unreliable result.
Question 5: What does Arrays.fill(values, 7) do?
Answer: It assigns 7 to every element in values.
Question 6: Does Arrays.copyOf(values, values.length) return the same array object?
Answer: No. It creates a new array object containing the copied elements.
Question 7: What does Arrays.equals(a, b) check?
Answer: It checks whether the arrays contain equal elements in the same order.
Question 8: What do the signs of Arrays.compare(a, b) indicate?
Answer: Negative means a is lexicographically less than b; zero means they compare equally; positive means a is lexicographically greater than b.
14. Frequently Asked Questions (FAQs)
1. What is the Java Arrays class?
It is a utility class in java.util that provides static methods for common array operations.
2. Do I need to create an object of Arrays?
No. The methods discussed here are static, so call them using the class name.
3. Does Arrays.sort() change the original array?
Yes. It sorts the array passed to it.
4. Can Arrays.binarySearch() be used on an unsorted array?
It can be called, but its result is not reliable unless the array is sorted according to the expected ordering.
5. How can I print all elements of an integer array?
Use System.out.println(Arrays.toString(arrayName));.
6. What is the difference between Arrays.equals() and Arrays.compare()?
equals() checks whether corresponding elements are equal and the arrays have the same length. compare() provides a lexicographic ordering result.
7. What is the difference between Arrays.copyOf() and assigning one array variable to another?
Arrays.copyOf() creates a new array. Assignment such as int[] b = a; makes both variables refer to the same array object.
8. Is Arrays.compare() available in Java 8?
No. Arrays.compare() was introduced in Java 9. Use methods supported by your Java version.
15. Quick Revision
Arraysbelongs tojava.util.- Import it with
import java.util.Arrays;. Arrays.toString()prints a readable representation of a 1D array.Arrays.sort()sorts the supplied array in ascending order.Arrays.binarySearch()searches a sorted array.Arrays.fill()assigns a value to every element or to a selected range.Arrays.copyOf()creates a new array with the requested length.Arrays.equals()checks content equality in order.Arrays.compare()compares arrays lexicographically and requires Java 9 or later.- Use
Arrays.deepToString()to display nested arrays. - Check a binary-search result before treating it as an index.
16. Conclusion
The Arrays utility class makes everyday array programming in Java easier by providing ready-made methods for displaying, sorting, searching, filling, copying, and comparing arrays. Understand whether each method changes the original array or returns a result, and remember to sort an array before using binary search. Practicing these methods will help you write shorter, clearer, and more reliable Java programs.