Menu

Java Arrays: Declare, Initialize, Access, and Loop

How arrays work in Java - fixed length, declaring and initializing them, indexing, length, looping, multidimensional arrays, and the Arrays helper class.

This page includes runnable editors - edit, run, and see output instantly.

An Array Is a Fixed-Size List

An array in Java holds a fixed number of values of the same type, laid out in order and accessed by position. "Fixed" is the key word: once you create an array, its length never changes. And "same type": an int[] holds only int values, a String[] holds only strings. That rigidity is the trade-off for arrays being fast and memory-compact.

You declare an array type by putting [] after the element type, then either assign a literal or allocate one with new:

The brackets can sit after the type (int[] scores) or after the name (int scores[]). Both compile, but int[] scores is the idiomatic Java style - put the [] with the type, where it belongs.

Creating an Array with new

When you don't know the values yet but you do know the size, use new. This allocates the slots and fills them with the type's default value:

The defaults aren't random garbage - Java zero-initializes every element. Numeric types start at 0 (or 0.0), boolean starts at false, and reference types like String start at null. That null is worth remembering: a freshly allocated String[] is full of nulls, and calling a method on one of them throws a NullPointerException.

Indexing Starts at Zero

You read and write elements by index, counting from 0. The last valid index is always length - 1:

Unlike arrays in some scripting languages, going out of range doesn't quietly give you null or undefined - it throws. Try reading an index that doesn't exist:

That program crashes with:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3

This is one of the most common beginner errors. The fix is almost always an off-by-one mistake in a loop condition - using <= where you meant <.

length Is a Field, Not a Method

Every array carries its size in a length field. Note: no parentheses.

Here's a gotcha that bites everyone at least once: arrays use .length (a field), but a String uses .length() (a method). Writing nums.length() on an array is a compile error, and writing text.length on a string is too. Same word, different rules - the array one has no parentheses.

Looping Through an Array

You learned the for-each loop on the previous page, and it's the cleanest way to read every element when you don't need the index:

When you need the index - to print position numbers, modify elements in place, or iterate backward - reach for the classic indexed for loop with length as the bound:

The condition is i < names.length, not <=. Using <= runs one step too far and throws the out-of-bounds exception from the section above. A quick rule: for-each when you only read values, indexed for when you need the position or want to write back into the array.

Multidimensional Arrays

A 2D array is really an array of arrays - think of it as a grid of rows and columns. You add a second pair of brackets:

grid[row][column] picks a single cell. Because each row is its own array, grid.length is the number of rows and grid[0].length is the number of columns in the first row. Rows don't even have to be the same length (that's called a jagged array), though most grids are rectangular.

The Arrays Helper Class

Arrays themselves have almost no methods - you can't sort or print one directly in a useful way. Java provides a java.util.Arrays utility class full of static helpers for exactly this:

A few things to lean on here. Arrays.toString(arr) is the right way to print an array - printing one directly gives you a useless string like [I@1b6d3586. Arrays.sort sorts in place. Arrays.copyOf is how you "resize": it returns a new array of the length you ask for, padding with defaults (the two extra slots above are 0). And Arrays.binarySearch only works correctly on an already-sorted array.

Arrays vs ArrayList

Use a plain array when the size is known up front and won't change - a fixed set of weekdays, a game board, pixel data. Arrays are fast and lightweight, but their fixed length is a real limit: you can't add a seventh element to a length-6 array without building a whole new one.

The moment you need to add and remove items freely, an array becomes awkward. That's what ArrayList is for - a resizable, growable list that handles the copying for you.

Next: ArrayList

When you don't know how many items you'll have, or that number changes as your program runs, a fixed-length array gets in the way. ArrayList is Java's answer: a list that grows and shrinks on demand, with add and remove methods instead of index juggling. That's up next.

Frequently Asked Questions

How do you declare and initialize an array in Java?

Declare the type with brackets and assign a literal: int[] nums = {1, 2, 3};. To create an empty array of a fixed size, use new: int[] nums = new int[5]; - that gives you 5 slots, each filled with the default value (0 for int, null for objects).

How do I get the length of an array in Java?

Use the length field (no parentheses): nums.length. It's a field, not a method, so nums.length() is a compile error. Note that String uses .length() with parentheses, but arrays use .length without - a classic mix-up.

Can a Java array change size after it's created?

No. A Java array has a fixed length set when it's created and you cannot grow or shrink it. If you need a resizable list, use an ArrayList instead. To "resize" an array you'd create a new, larger one and copy the elements over.

What is ArrayIndexOutOfBoundsException in Java?

It's the runtime error you get when you access an index that doesn't exist - below 0 or >= array.length. Unlike some languages, Java doesn't return a default or null for out-of-range access; it throws. Valid indexes always run from 0 to length - 1.

Coddy programming languages illustration

Learn to code with Coddy

GET STARTED