Skip to content

Arrays — Declaration, Initialization, Multi-Dimensional, and the Arrays Utility Class

DodaTech Updated 2026-06-28 6 min read

In this tutorial, you will learn about Arrays. We cover key concepts, practical examples, and best practices to help you master this topic.

Java arrays are fixed-length containers that hold elements of a single type, providing fast indexed access. Arrays are the simplest and most memory-efficient data structure in Java — every element is stored contiguously in memory, so accessing element i is an O(1) operation regardless of array size.

What You'll Learn

  • Array declaration and initialization syntax
  • Accessing, iterating, and copying arrays
  • Multi-dimensional and jagged arrays
  • The Arrays utility class for common operations

Why It Matters

Arrays are the foundation of the Collections Framework (ArrayList is backed by an array), and they appear in virtually every Java program. Understanding arrays deeply helps you write more efficient code and debug issues like ArrayIndexOutOfBoundsException.

Real-World Use

Network buffers use byte[], image processing uses int[][][] (3D pixel arrays), Sorting Algorithms operate on arrays, and Java's main method receives command-line arguments as String[].


Declaring Arrays

int[] numbers;      // preferred style: type followed by brackets
int numbers[];      // C-style: works but is less idiomatic in Java

At declaration time, you cannot specify the size. The array is null until initialized.

Initializing Arrays

Using new

int[] numbers = new int[5];  // array of 5 ints, all default (0)
numbers[0] = 10;
numbers[1] = 20;

Elements are initialized to their type's default value (0 for numeric, false for boolean, null for references).

Using an Initializer

int[] numbers = {10, 20, 30, 40, 50}; // size inferred: 5

Anonymous Array

printArray(new int[]{1, 2, 3});  // no variable name needed

Accessing Elements

Use zero-based indexing:

int[] numbers = {10, 20, 30};
System.out.println(numbers[0]); // 10
System.out.println(numbers[2]); // 30
System.out.println(numbers[3]); // ArrayIndexOutOfBoundsException

The array length is fixed after creation — accessed via numbers.length (not a method, a field):

for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}

Iterating Arrays

Indexed for Loop

for (int i = 0; i < numbers.length; i++) {
    numbers[i] = numbers[i] * 2; // modify elements
}

Enhanced for-each Loop

for (int num : numbers) {
    System.out.println(num); // read-only
}

The for-each loop cannot modify the array elements because num is a copy of each element.

Multi-Dimensional Arrays

Rectangular Arrays

int[][] matrix = new int[3][4];  // 3 rows, 4 columns
matrix[0][0] = 1;
matrix[2][3] = 42;

Iterate with nested loops:

for (int row = 0; row < matrix.length; row++) {
    for (int col = 0; col < matrix[row].length; col++) {
        System.out.print(matrix[row][col] + " ");
    }
    System.out.println();
}

Jagged Arrays

Each row can have a different length:

int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[5];
jagged[2] = new int[1];

Copying Arrays

Using a Loop

int[] source = {1, 2, 3, 4, 5};
int[] target = new int[source.length];
for (int i = 0; i < source.length; i++) {
    target[i] = source[i];
}

Using System.arraycopy

More efficient than a manual loop:

System.arraycopy(source, 0, target, 0, source.length);

Parameters: source array, source start index, target array, target start index, count.

Using Arrays.copyOf

Creates a new array, copying the specified number of elements:

int[] copy = Arrays.copyOf(source, source.length);
int[] firstThree = Arrays.copyOf(source, 3);     // {1, 2, 3}
int[] extended = Arrays.copyOf(source, 10);       // extra elements are 0

Using Arrays.copyOfRange

int[] middle = Arrays.copyOfRange(source, 1, 4);  // {2, 3, 4}

The Arrays Utility Class

java.util.Arrays provides static methods for common array operations:

int[] numbers = {5, 3, 1, 4, 2};
Arrays.sort(numbers);                           // {1, 2, 3, 4, 5}
int index = Arrays.binarySearch(numbers, 3);    // 2 (must be sorted first)
Arrays.fill(numbers, 0);                        // all elements become 0
boolean equal = Arrays.equals(a, b);            // element-by-element comparison
String str = Arrays.toString(numbers);          // "[1, 2, 3, 4, 5]"

For multi-dimensional arrays:

int[][] matrix = {{1, 2}, {3, 4}};
String deepStr = Arrays.deepToString(matrix);   // "[[1, 2], [3, 4]]"
boolean deepEq = Arrays.deepEquals(m1, m2);     // deep comparison

Parallel Sorting (Java 8+)

Arrays.parallelSort(largeArray);  // uses ForkJoinPool for large arrays

Varargs and Arrays

Varargs (...) is syntactic sugar for arrays:

public static int sum(int... numbers) {
    int total = 0;
    for (int n : numbers) {
        total += n;
    }
    return total;
}

int result = sum(1, 2, 3, 4);     // 10
int result2 = sum(new int[]{1, 2}); // also works

Common Mistakes

  1. Using length() instead of length. length is a field for arrays, not a method. length() is for String. Using the wrong one causes a compile error.
  2. Off-by-one with array.length. Valid indices are 0 to length - 1. array[array.length] throws ArrayIndexOutOfBoundsException.
  3. Assigning array references incorrectly. int[] b = a; does not copy — it creates a second reference to the same array. Use Arrays.copyOf() for a true copy.
  4. Using == to compare arrays. a == b compares references, not contents. Use Arrays.equals() for value comparison.
  5. Creating a generic array. new T[10] does not work due to type erasure. You must use (T[]) new Object[10] with a warning.

Practice Questions

1. What is the default value of an int array element?
0. Each element is initialized to 0 for int, false for boolean, \u0000 for char, and null for reference types.

2. How do you copy an array without sharing references?
Use Arrays.copyOf(), System.arraycopy(), or clone the array. Simply assigning int[] b = a; creates another reference to the same array.

3. What is a jagged array?
A multi-dimensional array where each row can have a different length. For example, new int[3][] where jagged[0] = new int[2]; jagged[1] = new int[5];.

4. Why does Arrays.toString() exist but array.toString() returns a hash?
Arrays inherit Object.toString(), which returns [Type@hash]. Arrays.toString() is a utility that returns a human-readable representation like [1, 2, 3].

5. What is the difference between length and length()?
array.length is a field (no parentheses). string.length() is a method (with parentheses). They are unrelated.

Challenge Question:
Write a method int[][] rotate90(int[][] matrix) that rotates a square matrix 90 degrees clockwise in-place. Use only O(1) extra space. Test it on a 3x3 and 4x4 matrix, printing the result with Arrays.deepToString().

FAQ

Can arrays hold different types?

No, a Java array is homogeneous — all elements must be the same type (or a subtype of the declared type for reference arrays). For mixed types, use Object[] and cast when retrieving.

Are arrays objects in Java?

Yes. Arrays are objects that inherit from Object. They have a length field, can be assigned to Object, and you can call methods like clone() on them. However, they cannot be subclassed.

What happens if I access index -1?

You get an ArrayIndexOutOfBoundsException. Java performs bounds checking at runtime for all array accesses. This prevents memory corruption but has a small performance cost.

What is the maximum size of a Java array?

The theoretical maximum is Integer.MAX_VALUE elements (2^31 - 1), but practical limits depend on available heap memory. A byte[] of max size would require ~2GB. Some JVM implementations impose additional limits.

How do I convert an int[] to List?

Use Arrays.stream(intArray).boxed().collect(Collectors.toList()). Each primitive is boxed into an Integer object. For reference types like String[], use Arrays.asList(stringArray).

Mini Project

Write a program ArrayPlayground.java that:

  1. Creates an int[] of size 20, filled with random numbers between 1 and 100
  2. Prints the array using Arrays.toString()
  3. Sorts it and prints again
  4. Searches for a value using binarySearch
  5. Copies the array into a larger array (size 25) using Arrays.copyOf()
  6. Fills the extra elements with -1 using Arrays.fill()
  7. Creates a 2D multiplication table (10x10) using a jagged array with each row length = row index + 1, and prints it

Run the program multiple times to verify the random values change but the logic always works.

What's Next

Arrays store data, but methods manipulate it. Lesson 9 explores methods — how to define reusable blocks of code, pass parameters, return values, overload methods, use varargs, and reference methods with the :: operator.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro