Lesson 67 min read
Arrays
Line up your data in neat, numbered rows
What's an Array?
An array is like a row of mailboxes in an apartment building. Each mailbox has a number (starting at 0), and each one holds exactly one item. When you create an array, you decide two things: what type goes in the boxes, and how many boxes you need.
Once you set the size, it's locked in β this is what makes them a static array. You can't add more mailboxes later β that's a job for ArrayList (a dynamic array that resizes itself). But arrays are fast, simple, and everywhere in Java.
Creating & Using Arrays
Useful Array Tricks
Java's Arrays utility class (from java.util.Arrays) gives you handy shortcuts:
Arrays.toString()β prints the array nicely instead of a weird memory address.Arrays.sort()β sorts the array in ascending order in-place.Arrays.fill()β fills every slot with the same value.Arrays.copyOf()β creates a copy of the array (optionally with a different size).
Arrays Utility Methods
Multidimensional Arrays β Grids & Tables
Note: Array indexes start at 0, not 1. An array of size 5 has indexes 0 through 4. Trying to access index 5 gives you an
ArrayIndexOutOfBoundsException β Java's way of saying "that mailbox doesn't exist!" This is the most common array bug.Challenge
Quick check
Continue reading