Back to Arrays
Q1Question 1 of 4

What are the array declaration and initialization forms in Java?

Key Concepts
  • Arrays are fixed-size, type-safe containers stored contiguously on the heap
  • Declaration: int[] arr; or int arr[]; (prefer int[] style)
  • Creation: new int[5] allocates with default values (0/null/false)
  • Initialization: int[] arr = {10, 20, 30}; or new int[]{10, 20, 30}
  • Length is fixed at creation – cannot grow or shrink – use ArrayList for dynamic sizing
  • Array index starts at 0, accessing out of bounds throws ArrayIndexOutOfBoundsException

Definition

An array is a fixed-size, indexed container of elements of the same type. Declare with int[], create with new int[n], initialize with {values}.

Array basics:

  • Fixed size. Set at creation, cannot change.
  • Type-safe. int[] holds only ints. String[] holds only Strings.
  • Zero-indexed. First element at index 0, last at length-1.
  • Heap-allocated. The array object lives on the heap. Elements are stored contiguously.

An array is a row of fixed-size bank lockers. You choose how many lockers when you build the row. Each locker is numbered starting from 0. You can put one item in each locker, and accessing a locker number that does not exist is an error.

Understanding the Concepts

Declaration and creation

Java offers several syntaxes for declaring and creating arrays. The brackets can appear after the type or after the variable name, but placing them after the type (int[]) is the preferred convention because it keeps the type information together.

JAVA
// Declare and create separately
int[] balances;
balances = new int[5];  // 5 elements, all initialized to 0

// Declare and create in one line
String[] accountIds = new String[3];  // 3 elements, all null

// Declare, create, and initialize
int[] amounts = {50000, 12000, 8000};  // size inferred as 3

// Alternative: new int[]{...} form (required when not at declaration)
int[] fees = new int[]{100, 200, 300};

The curly-brace initializer {50000, 12000, 8000} is only valid in a declaration statement. If you need to pass an array to a method or assign it later, use the new int[]{...} form.

Default values

When you create an array with new, every element is initialized to the type's default value. Primitive arrays get 0, false, or the null character. Object arrays get null.

JAVA
int[] nums = new int[3];              // [0, 0, 0]
boolean[] flags = new boolean[2];     // [false, false]
String[] names = new String[2];       // [null, null]
BigDecimal[] money = new BigDecimal[2]; // [null, null]

This means you must initialize object array elements before using them, or you risk a NullPointerException when calling methods on a null element.

Accessing elements and the length field

JAVA
int[] amounts = {50000, 12000, 8000};
System.out.println(amounts[0]);      // 50000 (first element)
System.out.println(amounts[2]);      // 8000 (last element)
System.out.println(amounts.length);  // 3 (a final field, not a method)

// amounts[3] → ArrayIndexOutOfBoundsException!

Note that length is a field, not a method. Strings use length() with parentheses, but arrays use length without.

Iterating

JAVA
// for-each (preferred when you do not need the index)
for (int amount : amounts) {
    System.out.println(amount);
}

// Traditional for (when you need the index)
for (int i = 0; i < amounts.length; i++) {
    System.out.println("Index " + i + ": " + amounts[i]);
}

Multi-dimensional arrays in banking

A two-dimensional array is an array of arrays. This is useful for representing tabular data like monthly transaction counts per branch.

JAVA
package com.bank.report;

public class BranchReport {
    public static void main(String[] args) {
        // 3 branches, 4 quarters
        int[][] txnCounts = {
            {1200, 1350, 1100, 1500},  // Branch 0: Mumbai
            {900,  980,  1050, 1100},  // Branch 1: Delhi
            {600,  650,  700,  750}    // Branch 2: Chennai
        };

        for (int branch = 0; branch < txnCounts.length; branch++) {
            int total = 0;
            for (int q = 0; q < txnCounts[branch].length; q++) {
                total += txnCounts[branch][q];
            }
            System.out.println("Branch " + branch + " annual txns: " + total);
        }
    }
}
TEXT
Branch 0 annual txns: 5150
Branch 1 annual txns: 4030
Branch 2 annual txns: 2700

What exceptions can occur?

Arrays throw two main exceptions. ArrayIndexOutOfBoundsException occurs when you access an index that does not exist. ArrayStoreException occurs when you try to store the wrong type in a covariant array.

JAVA
// ArrayIndexOutOfBoundsException
int[] arr = new int[3];
arr[3] = 10;  // index 3 does not exist – throws at runtime

// ArrayStoreException (covariance trap)
Object[] accounts = new String[3];  // compiles (covariance)
accounts[0] = 42;  // throws ArrayStoreException – int is not a String

What should a senior engineer know?

  • Arrays are objects. amounts instanceof Object is true. amounts.getClass() returns [I (int array class).
  • Arrays are covariant. Object[] arr = new String[3] compiles but risks ArrayStoreException. Generics are invariant: List does not accept List.
  • Prefer ArrayList for dynamic sizing. Arrays are for fixed-size, performance-critical code and varargs.
  • Arrays.copyOf() creates a resized copy: int[] bigger = Arrays.copyOf(arr, arr.length * 2).
  • System.arraycopy() is the fastest way to copy array segments – it is a native method.
  • Arrays.sort() and Arrays.binarySearch() are the standard utilities. For object arrays, the elements must implement Comparable or you must supply a Comparator.
  • What are common mistakes?

    A common mistake is confusing array length with the last valid index. The last valid index is always length - 1, not length.

    JAVA
    package com.bank.service;
    
    import java.math.BigDecimal;
    
    public class FeeCalculator {
        public BigDecimal getLastFee(BigDecimal[] fees) {
            // WRONG: off-by-one error
            // return fees[fees.length];  // ArrayIndexOutOfBoundsException!
    
            // CORRECT
            return fees[fees.length - 1];
        }
    }
    

    Another common mistake is modifying an array that was passed as a parameter, which mutates the caller's data because arrays are reference types.

    JAVA
    // WRONG: mutates the caller's array
    public void zeroBelowMinimum(BigDecimal[] balances, BigDecimal minimum) {
        for (int i = 0; i < balances.length; i++) {
            if (balances[i].compareTo(minimum) < 0) {
                balances[i] = BigDecimal.ZERO;  // modifies original!
            }
        }
    }
    
    // CORRECT: work on a copy
    public BigDecimal[] zeroBelowMinimum(BigDecimal[] balances, BigDecimal minimum) {
        BigDecimal[] copy = Arrays.copyOf(balances, balances.length);
        for (int i = 0; i < copy.length; i++) {
            if (copy[i].compareTo(minimum) < 0) {
                copy[i] = BigDecimal.ZERO;
            }
        }
        return copy;
    }
    

    Visual Overview

    DIAGRAM
      int[] amounts = new int[3];
        → heap: [0, 0, 0] (3 contiguous int slots)
        → amounts.length = 3 (fixed, cannot change)
        → amounts[0] = first, amounts[2] = last
        → amounts[3] = ArrayIndexOutOfBoundsException
    
      int[] amounts = {50000, 12000, 8000};
        → heap: [50000, 12000, 8000]
        → shorthand for new int[]{50000, 12000, 8000}
    

    Key Takeaway

    Arrays are fixed-size, type-safe containers stored contiguously on the heap. Declare with int[], create with new int[n], and initialize with {values}. Elements default to 0, false, or null. Accessing out of bounds throws ArrayIndexOutOfBoundsException.

    For dynamic sizing, use ArrayList. For fixed-size performance-critical code, use arrays.

    One sentence to remember: arrays are fixed-size, zero-indexed, heap-allocated – use ArrayList when you need dynamic sizing.

    ---

    Share
    Use ← → arrow keys to navigate