Arrays were honestly confusing to me at first. Not the concept — storing multiple values, fine. But all the utility methods scattered across different classes? That took a while to click.
Here's what I wish someone had just shown me early on.
First, the Two Classes You Need to Know
Most array utility methods live in java.util.Arrays — you need to import it.
For resizing and dynamic stuff, ArrayList is your friend (but that's a separate topic).
import java.util.Arrays;
Okay, let's get into it.
The Methods
Arrays.sort() — sorts your array in ascending order. Works for numbers and strings.
int[] nums = {5, 2, 8, 1, 9};
Arrays.sort(nums);
// nums is now {1, 2, 5, 8, 9}
Arrays.toString() — this one you'll use constantly for debugging. Prints array contents instead of some weird memory address.
int[] nums = {1, 2, 3};
System.out.println(nums); // [I@6d06d69c ← useless
System.out.println(Arrays.toString(nums)); // [1, 2, 3] ← useful
Arrays.fill() — fills all elements with a single value. Handy for initialization.
int[] grid = new int[5];
Arrays.fill(grid, 0);
// {0, 0, 0, 0, 0}
Arrays.copyOf() — copies an array into a new one. You can also resize it while copying.
int[] original = {1, 2, 3, 4, 5};
int[] copy = Arrays.copyOf(original, 3);
// copy = {1, 2, 3}
Arrays.copyOfRange() — copies a specific slice of the array.
int[] nums = {10, 20, 30, 40, 50};
int[] slice = Arrays.copyOfRange(nums, 1, 4);
// slice = {20, 30, 40}
Arrays.equals() — checks if two arrays have the same values in the same order.
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 lesson as strings — never use == to compare arrays.
Arrays.binarySearch() — searches for a value and returns its index. Sort the array first, otherwise results are unpredictable.
int[] nums = {1, 3, 5, 7, 9};
int index = Arrays.binarySearch(nums, 5);
// index = 2
array.length — not a method, it's a property. But you'll use it everywhere.
int[] nums = {4, 8, 15, 16, 23};
System.out.println(nums.length); // 5
No parentheses — just .length, not .length(). That trips up a lot of beginners.
Quick Reference
| Method | What it does |
|---|---|
Arrays.sort() |
Sort ascending |
Arrays.toString() |
Print readable format |
Arrays.fill() |
Set all values |
Arrays.copyOf() |
Copy (with resize option) |
Arrays.copyOfRange() |
Copy a slice |
Arrays.equals() |
Compare two arrays |
Arrays.binarySearch() |
Find index of a value |
.length |
Get array size |
One Thing to Remember
Arrays in Java have a fixed size — once created, you can't add or remove elements. If you need a resizable list, use ArrayList.
// Fixed size — can't grow
int[] arr = new int[5];
// Flexible — can add/remove
ArrayList<Integer> list = new ArrayList<>();
That's a whole other post though. 😄
Got questions or want me to cover ArrayList next? Drop a comment below!
Happy coding 🙌
Top comments (0)