Java Arrays Utility Class
Table of Contents + β
In the last lesson you learned about Java multidimensional arrays. You can build arrays and grids and loop over them by hand. But printing, sorting, copying, and comparing arrays are jobs you do all the time. Java already wrote those loops for you, in a class called java.util.Arrays.
π€ Why a whole class just for arrays?
You print, sort, fill, copy, compare, and search arrays all the time. Each one is a loop youβd rewrite, and each loop is a chance for an off-by-one bug. java.util.Arrays hands you those loops ready-made.
- Every method is
static, so you call it on the class name likeArrays.sort(...). NoArraysobject to create. - Shorter code means less to read and less to get wrong.
- Tested by millions, so the bugs are already gone.
- The name says the intent.
Arrays.sort(scores)reads as βsort the scoresβ at a glance.
Import the class once at the top of your file.
import java.util.Arrays;Now letβs meet the helpers, one at a time, each with code you can run.
π¨οΈ Arrays.toString: see your array
Print an array the obvious way and Java shows a strange code, not the values. This program prints an array directly, then the right way with Arrays.toString.
import java.util.Arrays;
public class ShowArray { public static void main(String[] args) { int[] scores = {90, 75, 60};
System.out.println(scores); // β prints a hashcode System.out.println(Arrays.toString(scores)); // β
prints the values }}- Line one prints
[I@1b6d3586, the arrayβs hashcode, a memory-style label, not the contents. Arrays.toStringwalks the array and builds a clean string of values in square brackets, comma-separated.- The hashcode differs each run, so ignore the exact letters.
Output
[I@1b6d3586[90, 75, 60]To read an array, always wrap it in Arrays.toString.
πΌ Arrays.sort: put it in order
A hand-written sort loop is fiddly and easy to get wrong. Arrays.sort does it for you, in place, in ascending order. This program sorts a jumbled array.
import java.util.Arrays;
public class SortDemo { public static void main(String[] args) { int[] numbers = {5, 1, 4, 2, 3};
Arrays.sort(numbers); // β
sorts the array itself, smallest first
System.out.println(Arrays.toString(numbers)); }}Arrays.sortchanges the original array. It does not hand back a new copy. After the call,numbersitself is in order.- It works for
double,char,String, and more, sorting in natural order: numbers low to high, words A to Z.
Output
[1, 2, 3, 4, 5]Want a different order, like largest first? Pass a second helper called a Comparator that tells sort how to compare two items. That needs object arrays like Integer[] or String[], not plain int[], and is a topic of its own.
Sort then search
A sorted array unlocks fast searching with Arrays.binarySearch, which we cover below. So sorting is often the first step, not the goal.
πͺ£ Arrays.fill: set every slot
Need a whole array set to one value, like every flag starting as true? Arrays.fill does it in one line instead of a loop. This program fills an array with 7.
import java.util.Arrays;
public class FillDemo { public static void main(String[] args) { int[] data = new int[5];
Arrays.fill(data, 7); // β
put 7 in every slot
System.out.println(Arrays.toString(data)); }}- A fresh
intarray starts full of 0. AfterArrays.fill(data, 7), all five slots hold 7. - A second version fills only part of the array (you pass a start and end index), but the whole-array form is what you reach for most.
Output
[7, 7, 7, 7, 7]π Arrays.copyOf and copyOfRange: copy and resize
Writing b = a does not copy. Both names point at the same array, so changing one changes the other. Arrays.copyOf makes a real, separate copy, and can grow or shrink it while copying. This program copies an array, then makes a longer copy.
import java.util.Arrays;
public class CopyDemo { public static void main(String[] args) { int[] original = {1, 2, 3};
int[] sameSize = Arrays.copyOf(original, 3); // exact copy int[] bigger = Arrays.copyOf(original, 5); // grow to length 5
System.out.println(Arrays.toString(sameSize)); System.out.println(Arrays.toString(bigger)); }}- The second number is the new arrayβs length.
- A bigger length fills the extra slots with the typeβs default value, which is 0 for numbers.
- A smaller length cuts the copy short. The original is never touched.
Output
[1, 2, 3][1, 2, 3, 0, 0]For just a slice, use Arrays.copyOfRange. You give a start and end index and get that piece back as a new array. This program pulls the middle of an array.
import java.util.Arrays;
public class RangeDemo { public static void main(String[] args) { int[] original = {10, 20, 30, 40, 50};
int[] slice = Arrays.copyOfRange(original, 1, 4); // index 1 up to 4
System.out.println(Arrays.toString(slice)); }}- The start index is included, the end index is not. So
(original, 1, 4)takes indexes 1, 2, 3, which are 20, 30, 40. - This βinclude start, exclude endβ rule is common across Java, so remember it.
Output
[20, 30, 40]π° Arrays.equals: compare contents
Another trap: == does not compare whatβs inside two arrays. It only checks if they are the very same array in memory. For the actual values, use Arrays.equals. This program compares two separate arrays holding the same numbers.
import java.util.Arrays;
public class EqualsDemo { public static void main(String[] args) { int[] a = {1, 2, 3}; int[] b = {1, 2, 3};
System.out.println(a == b); // β false, different objects System.out.println(Arrays.equals(a, b)); // β
true, same values }}a == bisfalse:aandbare two different arrays, even with equal values.Arrays.equals(a, b)walks both arrays and checks each value, so it returnstrue.- The rule: same length and same values in the same order means equal.
Output
falsetrueπ Arrays.binarySearch: find fast, but sort first
Arrays.binarySearch finds the index of a value very fast with a halving trick that only works on a sorted array. The rule: sort first, then search. This program sorts, then searches.
import java.util.Arrays;
public class SearchDemo { public static void main(String[] args) { int[] numbers = {40, 10, 30, 20, 50};
Arrays.sort(numbers); // β
must be sorted before searching
int index = Arrays.binarySearch(numbers, 30);
System.out.println(Arrays.toString(numbers)); System.out.println("Found 30 at index " + index); }}- After sorting, the array is
[10, 20, 30, 40, 50], and 30 sits at index 2, whichbinarySearchreturns. - If the value is missing, it returns some negative number (not exactly -1). So check βdid I find it?β by testing whether the result is zero or positive.
Output
[10, 20, 30, 40, 50]Found 30 at index 2Sorted or nothing
binarySearch trusts that the array is sorted. If it is not, you get a wrong or meaningless answer, with no error to warn you. Always sort first.
π Arrays.asList: array to List, with a catch
Arrays.asList turns an array into a List, handy when a method wants a List. But it has a famous gotcha. This program wraps a String array as a list and prints it.
import java.util.Arrays;import java.util.List;
public class AsListDemo { public static void main(String[] args) { String[] fruits = {"apple", "mango", "pear"};
List<String> list = Arrays.asList(fruits);
System.out.println(list); System.out.println("Has mango? " + list.contains("mango")); }}You can read it, loop it, and call contains on it.
Output
[apple, mango, pear]Has mango? trueNow the catch. The list is fixed-size, a thin view over the array, so adding or removing crashes at runtime. The line below shows the move that fails.
list.add("grape"); // β crashes with UnsupportedOperationExceptionIf you need a list you can grow or shrink, copy it into a real ArrayList first.
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
List<String> flexible = new ArrayList<>(Arrays.asList(fruits)); // β
now resizableflexible.add("grape"); // works fineπ§± Arrays.deepToString: print 2D arrays
Arrays.toString prints a 1D array, but on a 2D array each row is itself an array, so it prints a row of hashcodes. For grids, use Arrays.deepToString. This program prints a 2D array both ways.
import java.util.Arrays;
public class DeepDemo { public static void main(String[] args) { int[][] grid = { {1, 2, 3}, {4, 5, 6} };
System.out.println(Arrays.toString(grid)); // β prints row hashcodes System.out.println(Arrays.deepToString(grid)); // β
prints the grid }}Arrays.toStringsees two rows, but each row is an array, so it prints each rowβs hashcode.Arrays.deepToStringgoes one level deeper, printing every inner array as a readable grid. Use it any time you have an array of arrays.
Output
[[I@1b6d3586, [I@4554617c][[1, 2, 3], [4, 5, 6]]π The methods at a glance
A quick table of the helpers from this lesson.
| Method | What it does | Note |
|---|---|---|
| Arrays.toString(a) | Builds a readable string of the values | Use it to print any 1D array |
| Arrays.sort(a) | Sorts the array in ascending order | Changes the array in place |
| Arrays.fill(a, v) | Puts value v in every slot | Changes the array in place |
| Arrays.copyOf(a, n) | Makes a separate copy of length n | Can grow or shrink while copying |
| Arrays.copyOfRange(a, s, e) | Copies the slice from s up to e | Start included, end excluded |
| Arrays.equals(a, b) | True if same length and same values | Use instead of == for arrays |
| Arrays.binarySearch(a, v) | Returns the index of value v | The array must be sorted first |
| Arrays.asList(a) | Views the array as a List | Fixed-size, cannot add or remove |
| Arrays.deepToString(a) | Readable string of a 2D array | Use it for arrays of arrays |
β οΈ Common Mistakes
Traps that catch people first using this class.
- Printing an array directly. A plain
printlnshows a hashcode, not the values. Always wrap it inArrays.toString.
System.out.println(scores); // β prints something like [I@1b6d35System.out.println(Arrays.toString(scores)); // β
prints [90, 75, 60]- Searching an array that is not sorted.
binarySearchonly works on a sorted array, and gives no warning when it is wrong.
int index = Arrays.binarySearch(numbers, 30); // β if numbers is not sortedArrays.sort(numbers); // β
sort firstint index = Arrays.binarySearch(numbers, 30); // then search- Adding to an Arrays.asList list. That list is fixed-size, so adding or removing crashes.
List<String> list = Arrays.asList(fruits);list.add("grape"); // β crashes at runtimeList<String> ok = new ArrayList<>(Arrays.asList(fruits)); // β
resizable copyok.add("grape"); // works- Comparing arrays with ==. That checks identity, not contents. Use
Arrays.equalsfor values.
if (a == b) { } // β only true if they are the same objectif (Arrays.equals(a, b)) { } // β
checks the valuesβ Best Practices
Habits that make this class pay off.
- Import once, reuse everywhere. Put
import java.util.Arrays;at the top and lean on these helpers instead of loops. - Print with
Arrays.toStringandArrays.deepToString. Pick the deep one the moment your data has rows. - Sort before you binary search. Treat them as a pair, sort first every time.
- Use
Arrays.equalsto compare contents. Save==for βis it literally the same array?β. - Copy with
Arrays.copyOffor a separate array. Do not rely onb = a, which shares one array. - Wrap
Arrays.asListin anArrayListwhenever you might add or remove items later. - Let the helper name carry the meaning.
Arrays.sort(scores)beats a ten-line loop.
π§© What Youβve Learned
Nicely done. Letβs recap.
- β
java.util.Arraysis a box of static helpers for common array jobs. - β
Arrays.toStringprints a 1D array, andArrays.deepToStringprints a 2D array. - β
Arrays.sortorders an array in place, and unlocksArrays.binarySearch, which needs a sorted array. - β
Arrays.fillsets every slot,Arrays.copyOfmakes a separate copy that can resize, andArrays.copyOfRangetakes a slice. - β
Arrays.equalscompares values, unlike==which compares identity. - β
Arrays.asListviews an array as a list, but the list is fixed-size, so wrap it in anArrayListto grow it.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What does System.out.println(scores) print for an int array?
Why: Printing an array directly shows a hashcode, not the contents. Use Arrays.toString to see the values.
- 2
What must be true before you call Arrays.binarySearch?
Why: binarySearch only works correctly on a sorted array, so sort it first.
- 3
What happens if you call add on a list from Arrays.asList?
Why: Arrays.asList returns a fixed-size list, so adding or removing throws an exception. Wrap it in an ArrayList to resize.
- 4
Which method compares the actual values of two arrays?
Why: Arrays.equals checks length and values. The == operator only checks if they are the same object.
π Whatβs Next?
You have a full toolbox for arrays now: printing, sorting, copying, comparing, and searching. The next big building block is text. Almost every program reads, joins, and shapes words, and Java handles text with a type called String. Letβs start from the ground up.