LearnFrenzy
Sign in Take a free test

Java Programming · Topic 4 of 28

Arrays in Java

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Arrays in Java · Study material

An array in Java is a fixed-size, ordered block of elements of one type, reached by an index from 0 to length - 1. Arrays store marks of a class, prices of products, pixels of an image, a game board or the days of a month, and they are the foundation that ArrayList, HashMap and most other data structures are built on. Arrays also dominate coding interviews and placement tests: reversing, rotating, finding the second largest, frequency counting, two-sum, prefix sums and the maximum subarray. This page explains how arrays work in Java – including the fact that they are objects handled through references – the java.util.Arrays utility class, 2D and jagged arrays and the classic algorithms, with programs you can run. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – all compiled and run on Java 21.

On this page

  • Declaring, creating and initialising arrays; default values and length
  • Iterating with for and for-each; ArrayIndexOutOfBoundsException
  • Arrays are objects: references, clone() and Arrays.copyOf
  • The java.util.Arrays class: sort, binarySearch, fill, equals, toString …
  • 2D and jagged arrays
  • Array covariance and classic array algorithms

Declaring and creating arrays

int[] a declares a variable that can refer to an int array; new int[5] creates the array. Elements start with default values (0, 0.0, false, '\u0000' or null). An initialiser such as {91, 85, 78} creates and fills an array in one step. The size is fixed once created and available as the field length (no parentheses). Accessing an index outside 0 … length − 1 throws ArrayIndexOutOfBoundsException.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] marks = new int[5];                     // 5 ints, all 0 by default
        marks[0] = 91;
        marks[4] = 78;
        String[] names = {"Asha", "Ravi", "Meena"};   // array initialiser: size taken from the values
        double[] prices = new double[]{9.5, 12.0};
        boolean[] flags = new boolean[3];             // false, false, false
        char[] code = {'J', 'a', 'v', 'a'};

        System.out.println(Arrays.toString(marks) + " length " + marks.length);
        System.out.println(names[1] + " " + prices[prices.length - 1] + " " + Arrays.toString(flags));
        System.out.println(new String(code) + " " + code.length);

        try {
            System.out.println(marks[5]);             // valid indexes are 0 .. length - 1
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("error: " + e.getMessage());
        }
    }
}

Output

[91, 0, 0, 0, 78] length 5
Ravi 12.0 [false, false, false]
Java 4
error: Index 5 out of bounds for length 5

Iterating over arrays

Use the for-each loop when you only need the values, and an index loop when you need positions, want to change elements, iterate backwards or compare neighbours.

public class Main {
    public static void main(String[] args) {
        int[] sales = {120, 95, 140, 80, 160};

        int total = 0;
        for (int s : sales) total += s;                    // for-each: every element, read-only access

        int best = 0;
        for (int i = 1; i < sales.length; i++)             // index loop: when you need positions
            if (sales[i] > sales[best]) best = i;

        for (int i = sales.length - 1; i >= 0; i--) System.out.print(sales[i] + " ");   // backwards
        System.out.println();
        System.out.println("total " + total + ", average " + (double) total / sales.length
                + ", best day " + best + " (" + sales[best] + ")");
    }
}

Output

160 80 140 95 120
total 595, average 119.0, best day 4 (160)

Arrays are objects

An array variable holds a reference. Assigning it to another variable makes an alias, not a copy; passing it to a method lets the method change the caller's elements. To copy, use clone(), Arrays.copyOf or System.arraycopy. == and equals() on arrays compare references; Arrays.equals compares contents.

import java.util.Arrays;

public class Main {
    static void doubleAll(int[] a) {             // receives a copy of the REFERENCE: same array
        for (int i = 0; i < a.length; i++) a[i] *= 2;
    }

    static void replace(int[] a) {               // re-pointing the parameter does not affect the caller
        a = new int[]{0, 0, 0};
    }

    public static void main(String[] args) {
        int[] original = {1, 2, 3};
        int[] alias = original;                  // NOT a copy: both names refer to one array
        int[] copy = original.clone();           // a new array with the same values
        int[] longer = Arrays.copyOf(original, 5);

        alias[0] = 100;
        doubleAll(original);
        replace(original);

        System.out.println(Arrays.toString(original) + " " + Arrays.toString(alias));
        System.out.println(Arrays.toString(copy) + " " + Arrays.toString(longer));
        System.out.println((original == alias) + " " + (original == copy) + " " + original.equals(copy)
                + " " + Arrays.equals(new int[]{1, 2, 3}, copy));
    }
}

Output

[200, 4, 6] [200, 4, 6]
[1, 2, 3] [1, 2, 3, 0, 0]
true false false true

The java.util.Arrays class

MethodPurpose
Arrays.toString(a) / deepToString(a)readable text for 1D / nested arrays
Arrays.sort(a), sort(a, from, to), sort(objs, comparator)sort in place
Arrays.binarySearch(a, key)index of key in a sorted array (negative if absent)
Arrays.fill(a, v)set every element
Arrays.copyOf(a, n) / copyOfRange(a, from, to)copy (padding or truncating)
Arrays.equals(a, b) / deepEqualscompare contents
Arrays.asList(...)fixed-size List view of an object array
Arrays.stream(a)stream for sum, max, filter, map …
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        int[] a = {42, 7, 19, 88, 3, 56};
        Arrays.sort(a);                                        // ascending, in place
        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.binarySearch(a, 19) + " " + Arrays.binarySearch(a, 20));   // sorted array required

        int[] filled = new int[4];
        Arrays.fill(filled, 7);
        int[] middle = Arrays.copyOfRange(a, 1, 4);            // from index 1 up to (not including) 4
        System.out.println(Arrays.toString(filled) + " " + Arrays.toString(middle));

        String[] words = {"pear", "Apple", "fig", "banana"};
        Arrays.sort(words);                                    // natural order: uppercase before lowercase
        System.out.println(Arrays.toString(words));
        Arrays.sort(words, String.CASE_INSENSITIVE_ORDER);
        System.out.println(Arrays.toString(words));

        List<String> list = Arrays.asList(words);              // fixed-size List view backed by the array
        System.out.println(list.size() + " " + Arrays.stream(a).sum() + " " + Arrays.stream(a).max().getAsInt());
    }
}

Output

[3, 7, 19, 42, 56, 88]
2 -4
[7, 7, 7, 7] [7, 19, 42]
[Apple, banana, fig, pear]
[Apple, banana, fig, pear]
4 215 88

2D and jagged arrays

Java has no true 2D arrays: int[][] is an array of arrays. grid.length is the number of rows and grid[r].length the length of row r. Because each row is a separate array, rows can have different lengths – a jagged array, ideal for triangles and irregular data.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] grid = {
            {1, 2, 3},
            {4, 5, 6},
        };
        int rows = grid.length, cols = grid[0].length;
        int[][] t = new int[cols][rows];                    // transpose
        for (int r = 0; r < rows; r++)
            for (int c = 0; c < cols; c++) t[c][r] = grid[r][c];
        System.out.println(Arrays.deepToString(t));

        // Jagged array: each row is its own array and can have a different length
        int[][] triangle = new int[5][];
        for (int i = 0; i < triangle.length; i++) {
            triangle[i] = new int[i + 1];
            triangle[i][0] = triangle[i][i] = 1;
            for (int j = 1; j < i; j++) triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
        }
        for (int[] row : triangle) System.out.println(Arrays.toString(row));
    }
}

Output

[[1, 4], [2, 5], [3, 6]]
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]

Array covariance

A String[] can be assigned to an Object[] variable. That is convenient but unsafe: storing a non-String through the Object[] reference compiles and then fails at run time with ArrayStoreException. Generic collections avoid this problem by checking at compile time.

public class Main {
    public static void main(String[] args) {
        String[] strings = {"a", "b"};
        Object[] objects = strings;              // arrays are covariant: String[] IS-A Object[]
        System.out.println(objects.length + " " + objects.getClass().getSimpleName());
        try {
            objects[0] = 42;                     // compiles, but the real array only accepts Strings
        } catch (ArrayStoreException e) {
            System.out.println("ArrayStoreException: " + e.getMessage());
        }
        int[] nums = new int[0];                 // empty arrays are fine
        System.out.println(nums.length + " " + new int[3][4].length + " " + (new int[3][4])[0].length);
    }
}

Output

2 String[]
ArrayStoreException: java.lang.Integer
0 3 4

Arrays vs ArrayList

ArrayArrayList
Sizefixed at creationgrows and shrinks
Element typesprimitives or objectsobjects only (boxing for primitives)
Lengtha.lengthlist.size()
Accessa[i]list.get(i)
Best forfixed-size data, performance, primitives, matriceslists whose size changes

Common mistakes

  • i <= a.length in loops – the last valid index is length − 1.
  • a.length() – length is a field for arrays (but a method for Strings).
  • Printing an array directly – shows something like [I@1b6d3586; use Arrays.toString.
  • b = a "copies" the array – it copies the reference.
  • Comparing with == or equals() – use Arrays.equals.
  • binarySearch on an unsorted array – wrong results.
  • Modifying the list from Arrays.asList with add/remove – UnsupportedOperationException.

Key points to remember

  • Arrays have a fixed size, indexes 0 … length − 1, and default-initialised elements.
  • length is a field; invalid indexes throw ArrayIndexOutOfBoundsException.
  • Array variables hold references: assignment aliases, methods can modify elements.
  • Copy with clone(), Arrays.copyOf or System.arraycopy; compare with Arrays.equals.
  • Arrays.sort, binarySearch, fill, toString and stream cover most everyday needs.
  • 2D arrays are arrays of arrays and may be jagged.

Frequently asked questions

Where are arrays stored in Java?

Arrays are objects, so they live on the heap; the variable holds a reference (which may itself be on the stack for a local variable).

Can an array's size be changed?

No. Create a new, larger array and copy (Arrays.copyOf), or use ArrayList.

What is the difference between int[] a and int a[]?

Both declare an int array; int[] a is the preferred style because the type is written in one place.

Where can I learn more?

Read Java Arrays and Java 2D Arrays, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links