Java Tutorial chapters (15)
  1. 01Java Introduction
  2. 02Java Variables & Data Types
  3. 03Java Control Statements
  4. 04Java OOPs Basics
  5. 05Java Inheritance & Polymorphism
  6. 06Java Abstraction & Interfaces
  7. 07Java Strings
  8. 08Java Arrays
  9. 09Java Exception Handling
  10. 10Java Collections Framework
  11. 11Java Multithreading
  12. 12Java 8 Features
  13. 13Java I/O & File Handling
  14. 14Java JDBC
  15. 15Java MCQ

Chapter 08

Java Arrays

4 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

An array stores a fixed number of values of the same type in contiguous memory.

This chapter covers one-dimensional arrays, 2D arrays, jagged arrays and the java.

util.

Arrays utility methods.

Arrays are the base of every data structure and the first topic in coding rounds: searching, sorting, matrices and two-pointer problems.

Storing marks, pixels of an image, game boards, lookup tables and input for algorithms.

1

Array in Java

An array is an object that holds a fixed number of elements of the same type, accessed by a zero-based integer index. Its size is fixed when it is created and is available through the length field (not a method).

In short: An array is a row of equal-sized lockers numbered from 0. You choose how many lockers when you build the row, and you cannot add more later.

Array: fixed slots with indexes

Think about it

Arrays give O(1) random access and are the building block of ArrayList, HashMap buckets, strings and matrices. A cinema row with fixed seat numbers: you can jump directly to seat 7 but cannot add an eleventh seat.

Declaration: int[] a; (preferred) or int a[];.

Creation: a = new int[5]; or combined int[] a = {1, 2, 3};.

Elements get default values: 0 for numeric types, false for boolean, '\u0000' for char and null for references (String[] gives null elements).

Arrays live on the heap even when the variable is local; the variable holds a reference.

Accessing an invalid index throws ArrayIndexOutOfBoundsException at run time; a negative size throws NegativeArraySizeException.

length is a field: `a.

length, but s.

length()` is the String method.

Assigning b = a copies the reference, not the elements; use clone(), `Arrays.

copyOf or System.

arraycopy` for a real copy.

Arrays are covariant (a String[] can be assigned to Object[]) which can cause ArrayStoreException.

An array of objects stores references, so each element must still be created with new.

Key points

  • Index: Position of an element, from 0 to length-1.
  • length: Public final field holding the array size.
  • Default value: 0, false, null or \u0000 depending on the element type.
  • Covariance: String[] is a subtype of Object[]; may throw ArrayStoreException.
  • Arrays are objects; they inherit from Object and are always on the heap.
  • Size is fixed. Use ArrayList when the size must grow.
  • for-each cannot change the array reference or give the index.
  • a.length (field) vs str.length() (method) vs list.size() (method).

Example

Code
Creating, traversing and copying arrays:
import java.util.Arrays;

public class ArrayBasics {
    public static void main(String[] args) {
        int[] marks = new int[5];                  // all 0
        String[] names = new String[2];            // all null
        boolean[] flags = new boolean[2];          // all false
        System.out.println(Arrays.toString(marks));  // [0, 0, 0, 0, 0]
        System.out.println(Arrays.toString(names));  // [null, null]
        System.out.println(Arrays.toString(flags));  // [false, false]

        int[] a = {12, 45, 7, 33, 89};
        int sum = 0, max = a[0];
        for (int x : a) {
            sum += x;
            if (x > max) max = x;
        }
        System.out.println(sum + " " + max);       // 186 89
        System.out.println(a.length);              // 5

        int[] alias = a;                           // same array
        alias[0] = 100;
        System.out.println(a[0]);                  // 100
        int[] copy = a.clone();                    // independent copy
        copy[0] = 1;
        System.out.println(a[0] + " " + copy[0]);  // 100 1

        try {
            System.out.println(a[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage()); // Index 5 out of bounds for length 5
        }
    }
}
2

Multidimensional Array in Java

A multidimensional array is an array whose elements are themselves arrays. The most common form is the two-dimensional array int[][], which models a table (matrix) of rows and columns.

In short: A 2D array is a table: first index picks the row, second index picks the column.

Think about it

Tables, images, chess boards and graphs (adjacency matrix) are 2D arrays. A spreadsheet: rows and columns, each cell found by row number and column number.

Java does not have true matrices; int[][] m = new int[3][4] is an array of 3 references, each pointing to an int[4].

Therefore `m.

length is the number of rows and m[i].

length` the number of columns of row i.

Initialise with {{1,2,3},{4,5,6}}.

Use nested for loops to traverse in row-major order.

`Arrays.

toString` on a 2D array prints object addresses; use `Arrays.

deepToString`.

Three or more dimensions follow the same idea (new int[2][3][4]).

Typical uses

matrix addition, transpose, multiplication, grids and game boards.

For a matrix of size r × c, the transpose has size c × r.

Key points

  • Row-major order: Traversing one full row before moving to the next row.
  • Matrix: Rectangular 2D array with the same number of columns in every row.
  • deepToString: Arrays method that prints nested arrays.
  • Transpose: Matrix whose rows are the columns of the original.
  • int[][] m = new int[r][c]; m.length = r, m[0].length = c.
  • Only the first dimension is mandatory when creating: new int[3][].
  • Arrays.toString(m) is useless for 2D; use Arrays.deepToString(m).

Example

Code
2D arrays: traversal, transpose and addition:
import java.util.Arrays;

public class Matrix2D {
    public static void main(String[] args) {
        int[][] m = {
            {1, 2, 3},
            {4, 5, 6}
        };
        System.out.println(m.length + " x " + m[0].length);   // 2 x 3

        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m[i].length; j++) {
                System.out.print(m[i][j] + " ");
            }
            System.out.println();
        }

        // Transpose: 2x3 becomes 3x2
        int[][] t = new int[3][2];
        for (int i = 0; i < 2; i++)
            for (int j = 0; j < 3; j++)
                t[j][i] = m[i][j];
        System.out.println(Arrays.deepToString(t));  // [[1, 4], [2, 5], [3, 6]]

        // Matrix addition
        int[][] a = {{1, 2}, {3, 4}};
        int[][] b = {{5, 6}, {7, 8}};
        int[][] c = new int[2][2];
        for (int i = 0; i < 2; i++)
            for (int j = 0; j < 2; j++)
                c[i][j] = a[i][j] + b[i][j];
        System.out.println(Arrays.deepToString(c));  // [[6, 8], [10, 12]]

        int[][][] cube = new int[2][3][4];
        System.out.println(cube[1][2].length);       // 4
    }
}
3

Jagged Array in Java

A jagged array is a multidimensional array in which the rows can have different lengths. It is created by giving only the first dimension and then allocating each row separately.

In short: A normal 2D array is a rectangle. A jagged array is a staircase or triangle where each row can be as long as you like.

Think about it

It avoids wasted space and models real data with uneven rows such as students taking a different number of subjects. A theatre with a curved front: the first row has fewer seats than the back rows.

Since a 2D array is an array of arrays, int[][] j = new int[3][]; creates three null row references.

You then write `j[0] = new int[1]; j[1] = new int[3]; ...

`.

Accessing a row before allocating it gives NullPointerException.

A jagged array saves memory when rows have different amounts of data, for example Pascal triangle, triangular matrices, or a list of words with different letter counts.

Always use `row.

length` (not a fixed number) in the inner loop to avoid ArrayIndexOutOfBoundsException.

You can also initialise it directly: int[][] j = {{1}, {2, 3}, {4, 5, 6}};.

Key points

  • Jagged / ragged array: Array of arrays with unequal row lengths.
  • Row allocation: Creating each inner array with new after the outer array exists.
  • Syntax: new int[rows][]; then new int[len] for each row.
  • Un-allocated rows are null.
  • Loop with m[i].length for each row.

Example

Code
Pascal triangle with a jagged array:
import java.util.Arrays;

public class JaggedDemo {
    public static void main(String[] args) {
        int[][] tri = new int[4][];
        for (int i = 0; i < tri.length; i++) {
            tri[i] = new int[i + 1];          // row i has i+1 elements
            tri[i][0] = tri[i][i] = 1;
            for (int j = 1; j < i; j++) {
                tri[i][j] = tri[i - 1][j - 1] + tri[i - 1][j];
            }
        }
        for (int[] row : tri) {
            System.out.println(Arrays.toString(row));
        }
        // [1]
        // [1, 1]
        // [1, 2, 1]
        // [1, 3, 3, 1]

        int[][] marks = {
            {80, 90},
            {70, 60, 85},
            {95}
        };
        for (int i = 0; i < marks.length; i++) {
            int sum = 0;
            for (int m : marks[i]) sum += m;
            System.out.println("Student " + i + " total = " + sum);
        }
        // 170, 215, 95

        int[][] j = new int[2][];
        // System.out.println(j[0].length);   // NullPointerException (row not created)
        System.out.println(j[0]);             // null
    }
}
4

Array Methods and Utilities

Arrays have no methods of their own except those inherited from Object, so the java.util.Arrays class and System.arraycopy provide utilities to sort, search, fill, copy, compare and print arrays.

In short: Arrays.xxx() is the helper toolbox you use for arrays: sort them, search them, copy them, print them.

Arrays helpers: sort · search · copy

Think about it

Hand-written loops for sorting, copying and printing are slow to write and easy to get wrong; these utilities are used daily. Sorting a list of scores, copying a leaderboard before editing it, searching for a roll number.

`Arrays.

sort(a)` sorts primitives with dual-pivot quicksort and objects with a stable merge-sort variant (TimSort); you can pass a Comparator for object arrays only (use Integer[], not int[], to sort in reverse with `Collections.

reverseOrder()`).

`Arrays.

binarySearch(a, key)` needs a sorted array and returns the index or -(insertionPoint) - 1 if absent.

`Arrays.

fill(a, v)` sets every element.

`Arrays.

copyOf(a, n)` returns a new array of length n (padding with defaults or truncating), copyOfRange(a, from, to) copies a range.

`Arrays.

equals(a, b) compares contents (while a.

equals(b)` compares references) and deepEquals handles nested arrays.

`Arrays.

toString / deepToString` print contents.

`Arrays.

asList(T...

)` returns a fixed-size List view backed by the array (cannot add/remove).

`Arrays.

stream(a).

sum()` gives quick aggregates.

`System.

arraycopy(src, srcPos, dest, destPos, length)` is the fastest native copy and works for overlapping ranges.

Key points

  • binarySearch: O(log n) search on a sorted array.
  • copyOf: Creates a new array with a given length.
  • arraycopy: Native method that copies a block of elements.
  • asList: Fixed-size List view over an object array.

Read more

Example

Code
java.util.Arrays in action:
import java.util.*;

public class ArrayUtilsDemo {
    public static void main(String[] args) {
        int[] a = {5, 2, 9, 1, 7};
        Arrays.sort(a);
        System.out.println(Arrays.toString(a));                  // [1, 2, 5, 7, 9]
        System.out.println(Arrays.binarySearch(a, 7));           // 3
        System.out.println(Arrays.binarySearch(a, 6));           // -4  (-(3)-1)

        int[] bigger = Arrays.copyOf(a, 7);
        System.out.println(Arrays.toString(bigger));             // [1, 2, 5, 7, 9, 0, 0]
        System.out.println(Arrays.toString(Arrays.copyOfRange(a, 1, 4))); // [2, 5, 7]

        int[] z = new int[4];
        Arrays.fill(z, -1);
        System.out.println(Arrays.toString(z));                  // [-1, -1, -1, -1]

        int[] p = {1, 2, 3}, q = {1, 2, 3};
        System.out.println(p == q);                              // false
        System.out.println(p.equals(q));                         // false
        System.out.println(Arrays.equals(p, q));                 // true

        Integer[] boxed = {3, 8, 1};
        Arrays.sort(boxed, Collections.reverseOrder());
        System.out.println(Arrays.toString(boxed));              // [8, 3, 1]

        String[] words = {"pear", "fig", "banana"};
        Arrays.sort(words, Comparator.comparing(String::length));
        System.out.println(Arrays.toString(words));              // [fig, pear, banana]

        List<String> view = Arrays.asList(words);
        view.set(0, "kiwi");                                     // allowed, writes through
        System.out.println(words[0]);                            // kiwi
        // view.add("x");   // UnsupportedOperationException

        int[] dest = new int[5];
        System.arraycopy(a, 0, dest, 1, 3);
        System.out.println(Arrays.toString(dest));               // [0, 1, 2, 5, 0]
        System.out.println(Arrays.stream(a).sum());              // 24
    }
}

Sorting

Arrays.

sort(a), Arrays.

sort(a, from, to), Arrays.

sort(objArray, comparator).

Searching

Arrays.

binarySearch on sorted data only.

Copying

copyOf, copyOfRange, clone, System.

arraycopy.

Comparing and printing

Arrays.

equals, deepEquals, toString, deepToString.

Solved examples

Example 01 · Basic

Find the largest and smallest values in int[] a = {12, 45, 7, 33, 89}.

Given Data:
    Required To Find:

    Maximum and minimum

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: Start max and min with a[0]
    Step 2: Loop through the rest
    Step 3: Update max if larger, min if smaller
    Final Answer: max = 89, min = 7

    Approach note: Initialising with a[0] (not 0) also works for negative numbers.

    Example 02 · Basic

    What is printed? int[] a = new int[3]; System.out.println(a[3]);

    Given Data:
      Required To Find:

      Result or exception

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: Valid indexes are 0, 1, 2
      Step 2: Index 3 is outside the array
      Final Answer: ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

      Approach note: The last valid index is length - 1.

      Example 03 · Intermediate

      Reverse an int array in place without creating a second array.

      Given Data:
        Required To Find:

        Reversed array

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Set i = 0 and j = n - 1
        Step 2: Swap a[i] and a[j] using a temporary variable
        Step 3: Move i++ and j-- until i >= j
        Final Answer: {1,2,3,4,5} becomes {5,4,3,2,1}

        Approach note: Only n/2 swaps are needed.

        Example 04 · Intermediate

        Print the Pascal triangle with 4 rows using a jagged array.

        Given Data:
          Required To Find:

          Triangle rows

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: Allocate new int[4][]
          Step 2: Row i gets length i + 1
          Step 3: Edges are 1; inner value = above-left + above
          Final Answer: [1] / [1, 1] / [1, 2, 1] / [1, 3, 3, 1]

          Approach note: Allocate each row before writing to it.

          Real-world applications

          Java

          Using Java Arrays in real projects

          Storing marks, pixels of an image, game boards, lookup tables and input for algorithms.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: a.equals(b) compares the contents of two arrays.

          Why this is wrong: Arrays inherit equals from Object, which compares references.

          ✅ Verified Truth: Use Arrays.equals(a, b) (or deepEquals for nested arrays).

          ⚠️ Exam Tip: Very common output question.

          ❌ Myth: Array size can grow when needed.

          Why this is wrong: The length is fixed at creation.

          ✅ Verified Truth: Create a bigger array (Arrays.copyOf) or use ArrayList.

          ⚠️ Exam Tip: Fixed size is the main difference array vs ArrayList.

          ❌ Myth: System.out.println(arr) prints the elements.

          Why this is wrong: It prints type and hash like [I@1b6d3586.

          ✅ Verified Truth: Use Arrays.toString(arr) or deepToString.

          ⚠️ Exam Tip: Remember: char[] is special in println and prints text.

          Revision notes

          An array stores a fixed number of values of the same type in contiguous memory. This chapter covers one-dimensional arrays, 2D arrays, jagged arrays and the java.util.Arrays utility methods.

          High-Yield Quick Revision Points

          1. Arrays: fixed size, same type, zero-based, objects on the heap
          2. Defaults: 0, false, null; length is a field
          3. 2D array is an array of arrays; m[i].length is the row length
          4. Jagged: new int[r][]; allocate each row
          5. Arrays.sort / binarySearch (sorted) / copyOf / fill / equals / toString
          6. a.equals(b) compares references; Arrays.equals compares content

          Practice questions

          Question 1 · MCQ (Interview / semester)

          What are the default values in new int[3]?

          Question 2 · MCQ (Interview / semester)

          How do you get the size of an array a?

          Question 3 · MCQ (Interview / semester)

          Which exception is thrown for a bad array index?

          Question 4 · MCQ (Interview / semester)

          Arrays.binarySearch requires the array to be:

          Question 5 · MCQ (Interview / semester)

          Which statement creates a jagged array?

          Question 6 · MCQ (Interview / semester)

          Which prints the content of a 2D array?