JavaBasicsbeginner
Updated:

Java Arrays: Declaration, Iteration and Common Operations

7 min read

A practical guide to Java arrays: how to declare and initialize them, iterate safely, work with 2D arrays, and use the Arrays utility class for real tasks.

TL;DR – Quick Answer

A Java array is a fixed-size container that holds elements of one type in contiguous, indexed slots starting at index 0. You declare one with type[] name, create it with new or a literal like {1, 2, 3}, and read its size from the length field. Once created, an array can never grow or shrink.

On This Page

An array is the first data structure you meet in Java: a fixed-size row of slots, all holding the same type, each reachable instantly by its index. Marks of 60 students, pixels in an image row, daily temperatures for a month — whenever you have "many values of one kind", an array is the simplest way to hold them.

Arrays also dominate fresher coding tests. Reverse an array, find the second largest, count duplicates — these questions assume you are completely fluent in declaring, filling and looping over arrays. This guide builds that fluency.

Declaring and creating arrays

Declaration and creation are separate steps, even when you write them on one line:

int[] marks;              // declaration: marks can point to an int array
marks = new int[5];       // creation: allocate 5 slots, all initialized to 0

double[] prices = new double[3];          // {0.0, 0.0, 0.0}
String[] cities = new String[2];          // {null, null}
int[] primes = {2, 3, 5, 7, 11};          // literal: size inferred as 5

Three things to notice. First, the size goes with new, never with the type — int[5] marks is not Java. Second, new fills every slot with the default value of the element type: 0 for numeric data types, false for boolean, null for objects. Third, the literal form {2, 3, 5, 7, 11} only works in the same statement as the declaration.

Java also accepts int marks[] (the C style), but int[] marks is the convention: the type is "int array", so the brackets belong with the type.

Arrays are objects. The variable marks holds a reference to the array on the heap, not the array itself — which is why assigning one array variable to another copies the reference, not the data. Both variables then point at the same array.

Indexing and the length field

Indexes run from 0 to length - 1. The size is available in the length field:

public class IndexBasics {
    public static void main(String[] args) {
        int[] marks = {72, 85, 64, 91, 78};

        System.out.println(marks[0]);              // 72 (first)
        System.out.println(marks[marks.length - 1]); // 78 (last)

        marks[2] = 70;                             // overwrite the third element
        System.out.println(marks[2]);              // 70
    }
}

Access by index is O(1): the JVM computes the memory offset directly, no scanning needed. That constant-time access is the array's superpower and the reason it underlies ArrayList internally.

Read marks[marks.length - 1] carefully — asking for marks[marks.length] (index 5 in a 5-element array) compiles fine but throws ArrayIndexOutOfBoundsException at runtime.

Common mistake: A common mistake beginners make is confusing the three size accessors: arrays use the field length, Strings use the method length(), and collections use size(). Writing marks.length() on an array will not compile. Say it as a rhyme if it helps: array-length, string-length-brackets, list-size.

Iterating over arrays

You will loop over arrays thousands of times in your career, so both idioms from the Java loops guide must be automatic. The indexed for when you need positions, for-each when you only need values:

public class MaxFinder {
    public static void main(String[] args) {
        int[] marks = {72, 85, 64, 91, 78};

        // for-each: read every value
        int max = marks[0];
        for (int m : marks) {
            if (m > max) {
                max = m;
            }
        }
        System.out.println("Highest mark: " + max);   // 91

        // indexed for: we need the position too
        int maxIndex = 0;
        for (int i = 1; i < marks.length; i++) {
            if (marks[i] > marks[maxIndex]) {
                maxIndex = i;
            }
        }
        System.out.println("Topper is student #" + (maxIndex + 1));  // #4
    }
}

The pattern in both halves — start with the first element, compare against the rest using an if from control statements — is the seed of half the array questions you will face: max, min, second largest, count above average.

Two-dimensional arrays

A 2D array is an array of arrays — think of a timetable or a matrix of rows and columns:

public class MatrixSum {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        int sum = 0;
        for (int i = 0; i < matrix.length; i++) {          // rows
            for (int j = 0; j < matrix[i].length; j++) {   // columns in row i
                sum += matrix[i][j];
            }
        }
        System.out.println("Sum of all elements: " + sum);  // 45
    }
}

matrix.length is the number of rows; matrix[i].length is the number of columns in row i. Because each row is its own array, rows can have different lengths — a jagged array — which is why the inner loop asks each row for its own length instead of assuming a fixed width.

The Arrays utility class

java.util.Arrays provides the operations arrays lack on their own. These five cover most day-to-day work:

Method What it does
Arrays.toString(arr) Readable printout: [72, 85, 64]
Arrays.sort(arr) Sorts in place, ascending
Arrays.binarySearch(arr, key) Fast search — array must be sorted first
Arrays.copyOf(arr, newLen) Copy into a new array of the given size
Arrays.fill(arr, value) Set every slot to one value
import java.util.Arrays;

public class ArraysDemo {
    public static void main(String[] args) {
        int[] marks = {72, 85, 64, 91, 78};

        Arrays.sort(marks);
        System.out.println(Arrays.toString(marks));   // [64, 72, 78, 85, 91]

        int pos = Arrays.binarySearch(marks, 85);
        System.out.println("85 found at index " + pos);  // 3

        int[] bigger = Arrays.copyOf(marks, 8);
        System.out.println(Arrays.toString(bigger));  // [64, 72, 78, 85, 91, 0, 0, 0]
    }
}

Notice how copyOf pads the extra slots with zeros — this copy-into-a-bigger-array trick is exactly how resizable structures grow, since a created array can never change size.

Pro tip: Arrays.binarySearch returns nonsense on an unsorted array — it does not throw an error, it just gives a wrong (often negative) index. Sort first, always. And for comparing two arrays, use Arrays.equals(a, b); the == operator only compares references, so two arrays with identical contents still come out "not equal".

Arrays of objects and String[]

Element types are not limited to primitives. The args parameter of main is a String array, and you can build arrays of your own classes:

String[] batch = {"Anil", "Divya", "Ravi"};
for (String name : batch) {
    System.out.println(name.toUpperCase());
}

One trap: new String[3] gives you three null slots, not three empty strings. Calling a method on an element before assigning it throws a NullPointerException. Fill object arrays before you use them.

Passing arrays to methods

Java passes everything by value — but for arrays, the value passed is the reference. The method receives a copy of the reference pointing at the same array, so changes to elements inside the method are visible to the caller:

static void applyBonus(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
        arr[i] += 5;                 // caller sees this change
    }
}

Call applyBonus(marks) and the original marks array is modified — there is only one array in memory. This surprises beginners who expect methods to work on private copies, and it cuts both ways. It is efficient, because a million-element array is never duplicated just to be read; and it is dangerous, because a method can silently mutate data its caller still depends on.

Reassigning the parameter, however, does nothing outside: writing arr = new int[10]; inside the method only repoints the local copy of the reference. The caller's variable still points at the original array. If a method must not touch the caller's data, hand it a defensive copy made with Arrays.copyOf — a pattern you will meet again when encapsulation comes up in OOP.

Array vs ArrayList: when fixed size hurts

The fixed size that makes arrays fast also makes them rigid. Add a sixth student to a five-slot array and you must allocate a new array and copy — every time. When data grows and shrinks, reach for a collection instead: an ArrayList resizes itself and adds rich behaviour like contains and remove. The trade-offs between the two, and against LinkedList, matter in interviews, so learn arrays first — collections make far more sense once you know what they are built on.

Interview note: "Where are arrays stored in Java?" — on the heap, always, even arrays of primitives, because arrays are objects. Expect follow-ups on default values (new int[5] is all zeros) and on what arr1 == arr2 compares (references, not contents). These three facts together answer most array theory questions.

What to practise next

Fluency comes from repetition, not reading. Work through this ladder: reverse an array in place, find the second largest without sorting, count how many elements exceed the average, rotate an array by k positions, then merge two sorted arrays. Every one of these uses only arrays, loops and if-conditions — and every one has appeared in real fresher screening tests.

At CodeBegun's Java Full Stack course in Hyderabad, this exact ladder is the week-two assignment set, because students who grind through it find collections, strings and even DSA rounds dramatically easier afterwards.

Frequently Asked Questions

How do you declare and initialize an array in Java?
Declare with the type and square brackets, for example int[] marks. Initialize either with new and a size, like new int[5], or with a literal such as int[] marks = {72, 85, 64}. With new, elements start at default values: 0 for numbers, false for boolean and null for objects.
Why do Java arrays start at index 0?
The index represents the offset from the start of the array in memory, and the first element sits at offset 0. This convention comes from C and means valid indexes run from 0 to length - 1. Accessing index length throws ArrayIndexOutOfBoundsException.
What is the difference between length and length() in Java?
Arrays expose a final field called length with no parentheses. Strings use a method called length() with parentheses, and collections like ArrayList use size(). Mixing these up is a classic compile error freshers hit in their first week.
Can you change the size of an array in Java?
No. Array size is fixed at creation and can never change. To simulate resizing you create a bigger array and copy elements across, typically with Arrays.copyOf. If you need a container that grows automatically, use an ArrayList, which manages that copying internally.
What is the difference between an array and an ArrayList?
An array has a fixed size, works with both primitives and objects, and offers no built-in operations beyond length. An ArrayList resizes automatically, offers methods like add, remove and contains, but stores only objects, so primitives get autoboxed. Arrays suit fixed-size, performance-critical data; ArrayList suits everything else.
How do you print a Java array?
Printing an array directly gives output like [I@1b6d3586, which is the type and hash code, not the contents. Use Arrays.toString(arr) for one-dimensional arrays and Arrays.deepToString(arr) for nested arrays to get readable output.

Want to Build Your Career in Java Full Stack with AI?

Join CodeBegun and train with working industry engineers — Explore the Program

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 14 July 2026 LinkedIn
Chat with us