Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Arrays in Java

Clear, exam-focused notes on Java arrays: what they are, how to declare/use them, important rules (indexing, defaults, covariance), common library methods, and three runnable example programs with exact input/output.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Arrays are the simplest container for many problems: they store a fixed-size sequence of values all of the same type and let an engineer perform bulk numeric, table, or sequence operations efficiently. In Java you will use arrays for numerical computation, storage of objects, implementing data-structure building blocks, and as the underlying representation for variable-length arguments (varargs).

Key ideas

Exact definition (as expected in exams): An array of component type T and length N is an object that stores N values each of type T, and provides O(1) access to the value at index i for integers 0 ≤ i < N. The array length N is fixed at creation time.

Important assumptions: a) elements are typically stored in contiguous element slots (a useful logical model; the Java Language Specification does not mandate physical contiguity). b) Java arrays are objects; array variables are references.

  • Element: An element is one item stored in an array. For primitive component types (int, double, boolean, etc.) the element is the primitive value. For reference component types (e.g. String, Object, MyClass) the element is a reference to an object.

  • Index: The integer position used to access an element. Access with bracket syntax a[i]. Valid indices are 0 through a.length - 1. Access outside the range throws ArrayIndexOutOfBoundsException at runtime.

  • Declaration, allocation, initialization: The common steps are: declare a variable to hold the array reference; allocate the array object with new; initialize elements explicitly or rely on default initialization.

    • Declaration syntax examples: int[] a; or int a[]; (both declare a variable that can refer to an int array).
    • Allocation: a = new int[5]; creates an array object with length 5.
    • Combined: int[] a = new int[5];
  • Default values: When an array is created with new, every element receives a default value: for numeric primitives the default is zero of the appropriate kind (0 for byte, short, and int, 0L for long, 0.0f for float, 0.0 for double), for char it is '\u0000', for boolean it is false, and for reference types it is null.

  • Length property: Arrays have a public final instance field length (not a method). Use a.length to get the array length.

  • Multidimensional arrays: Java supports multidimensional arrays as arrays of arrays. A two-dimensional array T[][] m is an array whose elements are T[]. This allows rectangular arrays (all rows same length) and jagged arrays (rows different lengths).

    Exactly state: A 2-D array is a reference to an array of references to 1-D arrays.

  • Arrays are objects: Every array is an instance of a class whose runtime type encodes the component type and number of dimensions. Arrays inherit from Object. Therefore a.getClass() and a instanceof Object apply. All array types implement Cloneable and java.io.Serializable. Primitive arrays are not compatible with Object[] (e.g., int[] is not an Object[]).

  • Identity and equality: == compares array references (identity), not element-wise equality. To compare contents use java.util.Arrays.equals for 1-D primitives/objects and Arrays.deepEquals for nested arrays.

  • Covariance and runtime checks: Arrays in Java are covariant: if S is a subtype of T, then S[] is a subtype of T[]. This is a compile-time relationship that allows assignments like Object[] o = new String[5];. However, storing into such arrays is checked at runtime and may throw ArrayStoreException if an incompatible type is assigned.

    Exact rule: For reference types R1 and R2, R1[] is assignable to R2[] if and only if R1 is assignable to R2.

  • Copying arrays: There are multiple ways: manual loops, System.arraycopy, Arrays.copyOf, and clone(). Important: clone() and Arrays.copyOf perform a shallow copy for arrays of references (they copy the references, not the objects). For primitives they copy values.

  • Common library helpers: Arrays.sort, Arrays.fill, Arrays.binarySearch, Arrays.equals, Arrays.deepEquals, Arrays.copyOf are commonly used. System.arraycopy is fast native copy used for performance-sensitive code. Note: Arrays.binarySearch requires the array to be sorted using the same order beforehand.

  • Varargs: A method declared void m(T... args) receives its args as an array T[] inside the method. Calling m(a, b, c) is compiled to passing an array of the three arguments. You can also pass an existing T[], and calling with no arguments passes a zero-length array.

  • Drawing to explain arrays (diagram to draw on answer script): For a one-dimensional int[] a = new int[4]; draw a horizontal row of 4 boxes. Under each box draw the index: 0, 1, 2, 3. Inside each box write its value (initially 0). To show reference semantics draw a separate box representing the variable a with an arrow to the array block (not to any specific element).

Formulas

  • Declare and allocate: T[] name = new T[n]; or T[] name = {v0, v1, v2}; for array literals. For assignment after declaration, use name = new T[]{v0, v1, v2};.
  • Access: name[i] where 0 ≤ i < name.length. Enhanced for loop: for (T x : name) { ... } iterates elements in index order.
  • Multi-dim allocation: T[][] m = new T[rows][]; then for each row m[i] = new T[rowLength]; (jagged allowed). Rectangular in one step: T[][] m = new T[rows][cols];.
  • Clone: T[] b = a.clone(); shallow copy for reference components.
  • System copy: System.arraycopy(src, srcPos, dest, destPos, length); copies length elements. Performs bounds and type checks; may throw IndexOutOfBoundsException, ArrayStoreException, or NullPointerException.

Explain symbols: T is a Java type (primitive or reference); name is an identifier; n, i, rows, rowLength are ints; srcPos, destPos, length are ints.

Worked examples

Example 1 — Sum and average of integer array (reads input)

import java.util.Scanner;
class SumAvg {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int[] a = new int[n];
    int sum = 0;
    for (int i = 0; i < n; i++) {
      a[i] = sc.nextInt();
      sum += a[i];
    }
    double avg = (n > 0) ? (double) sum / n : 0.0;
    System.out.printf("Sum = %d\nAverage = %.2f\n", sum, avg);
  }
}

Sample input:

5
2 4 6 8 10

Exact output:

Sum = 30
Average = 6.00

Example 2 — Jagged 2-D array creation and display (no input)

class JaggedDemo {
  public static void main(String[] args) {
    int[][] a = new int[3][]; // 3 rows
    a[0] = new int[1]; // row 0 length 1
    a[1] = new int[2]; // row 1 length 2
    a[2] = new int[3]; // row 2 length 3
    int val = 1;
    for (int i = 0; i < a.length; i++) {
      for (int j = 0; j < a[i].length; j++) {
        a[i][j] = val++;
      }
    }
    for (int i = 0; i < a.length; i++) {
      for (int j = 0; j < a[i].length; j++) {
        System.out.print(a[i][j] + " ");
      }
      System.out.println();
    }
  }
}

Exact output:

1 
2 3 
4 5 6 

Example 3 — Demonstrate clone() is a shallow copy for reference arrays

class Box { int v; Box(int v){this.v = v;} }
class CloneShallow {
  public static void main(String[] args) {
    Box[] orig = { new Box(10), new Box(20) };
    Box[] copy = orig.clone();
    // Modify the object referenced by orig[0]
    orig[0].v = 99;
    System.out.println("orig[0].v = " + orig[0].v);
    System.out.println("copy[0].v = " + copy[0].v);
  }
}

Exact output:

orig[0].v = 99
copy[0].v = 99

This shows that clone copied references, not the objects (shallow copy).

Common mistakes

  • Assuming == checks element-wise equality. == checks reference identity for arrays.
  • Expecting clone or Arrays.copyOf to deep-copy object graphs; they copy references (shallow copy).
  • Ignoring ArrayStoreException possibility when assigning into covariant arrays: Object[] o = new String[2]; o[0] = new Integer(5); fails at runtime.
  • Not initializing rows of a 2-D array created with new T[rows][] before accessing them.
  • Assuming arrays can change size after allocation. To change size, create a new array and copy elements.

For your exam

Types of questions you will get:

  • Definitions: define array, element, index, jagged array, shallow vs deep copy. Full-marks answer includes concise definition, valid index range, and example code or diagram.
  • Short notes: default initialization, arrays are objects, length property, covariance and ArrayStoreException. Include the precise default values, mention length is a field, and give a short code example showing the exception.
  • Derivations/diagrams: draw and explain layout of a 2-D jagged array and show where references point.
  • Programs: declare/allocate arrays, compute sum/average, find max/min, transpose a rectangular matrix, demonstrate clone behavior. Provide complete compilable code and sample I/O.
  • Comparisons: difference between clone(), System.arraycopy, and Arrays.copyOf (state shallow/deep behavior and complexity).

What a full-marks program answer includes:

  • Correct program header and imports, required classes and main method.
  • Correct handling of input and edge cases (zero length arrays).
  • Accurate output exactly matching expected format.
  • Comments or short explanation if asked.

Quick check

  1. Define an array and give the valid index range for int[] a = new int[10];.
  2. What is printed by:
int[] a = {1,2,3};
int[] b = a;
b[0] = 9;
System.out.println(a[0]);
  1. What is the default value of elements in new boolean[3]? Answers: 1) An array is a fixed-size ordered collection; indices 0..9. 2) 9. 3) false

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?