Arrays

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Arrays are objects that store multiple variables of the same type.
  • They have a fixed size; once an array is created, its length cannot be changed.
  • Elements are accessed via a zero-based index.

Concept

In Java, arrays are reference types (objects) dynamically created on the Heap, even if they hold primitive types (like int[]).

Declaration and Instantiation

You must specify the size of the array when you instantiate it, or provide the exact values in an array literal.

Multidimensional Arrays

Java supports multidimensional arrays, which are essentially arrays of arrays.

Examples

import java.util.Arrays;

public class ArrayExample {
    public static void main(String[] args) {
        // 1. Declaration and Allocation
        int[] numbers = new int[5]; // Array of 5 ints, all initialized to 0
        numbers[0] = 10;
        
        // 2. Array Literal (Initialization)
        String[] names = {"Alice", "Bob", "Charlie"};
        
        // 3. Multidimensional Array (Matrix)
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6}
        };
        
        // 4. Helper class: java.util.Arrays
        System.out.println(Arrays.toString(names)); // Prints [Alice, Bob, Charlie]
        Arrays.sort(names); // Sorts the array in-place
    }
}

Interview Questions

Q: What happens if you try to access an index that is outside the array’s bounds?
A: Java will throw an ArrayIndexOutOfBoundsException at runtime.

Q: Can you change the size of an array after it has been created?
A: No. Arrays in Java have a fixed length. If you need a resizable collection, you should use ArrayList (from the Collections Framework) which handles dynamic resizing under the hood.

Q: Why is an array a reference type?
A: In Java, arrays are treated as objects. They have attributes (like .length) and inherit from the Object class. A variable holding an array is just a reference (pointer) to the block of memory on the Heap where the contiguous array elements are stored.