An array holds a fixed number of values of one type under a single name. In Java, arrays are objects.

One-Dimensional Arrays

An array is declared with brackets, int[] marks; (or int marks[];), and created with new, which fixes its size: marks = new int[5];. Both can be done together: int[] marks = new int[5];. Elements are numbered from 0 to length − 1 and are reached by index: marks[0] = 78;. An array can be initialised with values: int[] marks = {78, 85, 62};. Every array has a length field. Java checks the index on every access, and an index outside the bounds throws an ArrayIndexOutOfBoundsException, which prevents memory errors. Elements of a new array get default values (0, false or null).

Definition: Array. An object that holds a fixed number of elements of the same type, accessed by an integer index from 0 to length minus 1.

Using Arrays

Arrays are processed with loops: for (int i = 0; i < a.length; i++) or the enhanced for (int x : a). Common tasks are finding the sum, average, largest and smallest, searching, reversing and sorting. The class java.util.Arrays provides ready methods: Arrays.sort(a), Arrays.toString(a) and Arrays.fill(a, v). Assigning one array variable to another copies the reference, not the elements; to copy elements, use a loop, clone() or Arrays.copyOf().

Two-Dimensional Arrays

A two-dimensional array is an array of arrays, used for tables and matrices: int[][] m = new int[3][4]; gives 3 rows and 4 columns, and m[i][j] is an element. It can be initialised as int[][] m = {{1, 2}, {3, 4}};. m.length gives the number of rows and m[i].length the number of columns in row i. Since each row is a separate array, rows may have different lengths, giving a jagged array. Nested loops process 2D arrays, as in matrix addition and multiplication.

Table 3.3: Array operations

Task Code Note
Declare and create int[] a = new int[5]; Size fixed
Initialise int[] a = {3, 1, 2}; Size 3
Length a.length A field, not a method
Sort Arrays.sort(a); Ascending order
2D element m[i][j] Row i, column j

Example 3.3: Reverse and matrix product

Problem: (a) Print the array {10, 20, 30, 40} in reverse. (b) Multiply the matrices {{1, 2}, {3, 4}} and {{5, 6}, {7, 8}}.

Solution:

  1. Loop from index length − 1 down to 0: 40 30 20 10.
  2. C[i][j] = sum of A[i][k] × B[k][j]: C[0][0] = 1·5 + 2·7 = 19, C[0][1] = 22, C[1][0] = 43, C[1][1] = 50.

Result: (a) 40 30 20 10, (b) {{19, 22}, {43, 50}}.

import java.util.Arrays;
public class ArrayDemo {
    public static void main(String[] args) {
        int[] a = {10, 20, 30, 40};
        for (int i = a.length - 1; i >= 0; i--)
            System.out.print(a[i] + " ");
        System.out.println();
        int[][] x = {{1, 2}, {3, 4}}, y = {{5, 6}, {7, 8}};
        int[][] c = new int[2][2];
        for (int i = 0; i < 2; i++)
            for (int j = 0; j < 2; j++)
                for (int k = 0; k < 2; k++)
                    c[i][j] += x[i][k] * y[k][j];
        System.out.println(Arrays.deepToString(c));
        int[] s = {42, 7, 19, 3};
        Arrays.sort(s);
        System.out.println(Arrays.toString(s));
    }
}

Output

40 30 20 10
[[19, 22], [43, 50]]
[3, 7, 19, 42]

Common mistakes

  • Using a.length() for arrays. It is a field: a.length.
  • Accessing a[a.length], which is out of bounds.
  • Copying an array with b = a and expecting a separate copy.

Key takeaways

  • Arrays are objects created with new and indexed from 0.
  • length gives the number of elements.
  • Out-of-range indexes throw ArrayIndexOutOfBoundsException.
  • A 2D array is an array of arrays; rows may differ in length.

Practice questions

  1. How do you find the number of elements in array a?
  2. What happens if an array index is out of bounds?
  3. What is a jagged array?

Answers to the practice questions

  1. With a.length.
  2. An ArrayIndexOutOfBoundsException is thrown.
  3. A 2D array whose rows have different lengths.

Sources

  • Official BCA syllabus Object Oriented Programming using Java, course code 25BCA402SEC01, Unit III