Java Arrays Utility Class

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 like Arrays.sort(...). No Arrays object 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.toString walks 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.sort changes the original array. It does not hand back a new copy. After the call, numbers itself 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 int array starts full of 0. After Arrays.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 == b is false: a and b are two different arrays, even with equal values.
  • Arrays.equals(a, b) walks both arrays and checks each value, so it returns true.
  • The rule: same length and same values in the same order means equal.

Output

false
true

πŸ”Ž 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, which binarySearch returns.
  • 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 2

Sorted 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? true

Now 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 UnsupportedOperationException

If 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 resizable
flexible.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.toString sees two rows, but each row is an array, so it prints each row’s hashcode.
  • Arrays.deepToString goes 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 println shows a hashcode, not the values. Always wrap it in Arrays.toString.
System.out.println(scores); // ❌ prints something like [I@1b6d35
System.out.println(Arrays.toString(scores)); // βœ… prints [90, 75, 60]
  • Searching an array that is not sorted. binarySearch only works on a sorted array, and gives no warning when it is wrong.
int index = Arrays.binarySearch(numbers, 30); // ❌ if numbers is not sorted
Arrays.sort(numbers); // βœ… sort first
int 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 runtime
List<String> ok = new ArrayList<>(Arrays.asList(fruits)); // βœ… resizable copy
ok.add("grape"); // works
  • Comparing arrays with ==. That checks identity, not contents. Use Arrays.equals for values.
if (a == b) { } // ❌ only true if they are the same object
if (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.toString and Arrays.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.equals to compare contents. Save == for β€œis it literally the same array?”.
  • Copy with Arrays.copyOf for a separate array. Do not rely on b = a, which shares one array.
  • Wrap Arrays.asList in an ArrayList whenever 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.Arrays is a box of static helpers for common array jobs.
  • βœ… Arrays.toString prints a 1D array, and Arrays.deepToString prints a 2D array.
  • βœ… Arrays.sort orders an array in place, and unlocks Arrays.binarySearch, which needs a sorted array.
  • βœ… Arrays.fill sets every slot, Arrays.copyOf makes a separate copy that can resize, and Arrays.copyOfRange takes a slice.
  • βœ… Arrays.equals compares values, unlike == which compares identity.
  • βœ… Arrays.asList views an array as a list, but the list is fixed-size, so wrap it in an ArrayList to grow it.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 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. 2

    What must be true before you call Arrays.binarySearch?

    Why: binarySearch only works correctly on a sorted array, so sort it first.

  3. 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. 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.

Introduction to Strings in Java

Share & Connect