Quiz 2
Registry Synced

Arrays in Java

2166 words
11 min read

Reading compass

Now · 🎯 Learning Objectives

Arrays in Java

🎯 Learning Objectives

By the end of this topic, you will be able to:
  • Declare, create, and initialize one-dimensional and multi-dimensional arrays
  • Iterate over arrays using both indexed and enhanced for loops
  • Understand the length property and array bounds
  • Use java.util.Arrays utility methods for sorting, searching, and filling
  • Use variable-length argument lists (varargs)
  • Recognize and avoid ArrayIndexOutOfBoundsException

📋 Prerequisites


1. Intuition: What Problem Do Arrays Solve?

1.1 The Problem

Without arrays, storing 100 test scores would require 100 separate variables:
java
int score1, score2, score3, ..., score100;  // Impossible!
An array lets you store many values of the same type under a single name, accessed by index:
java
int[] scores = new int[100];  // One variable, 100 values
scores[0] = 85;    // First score
scores[99] = 92;   // Last score

1.2 Mental Model: A Row of Lockers

An array is like a row of numbered lockers in a school hallway:
  • Each locker holds one item (all the same type)
  • Each locker has a unique number (index), starting at 0
  • You know how many lockers there are (length)
  • Opening a non-existent locker (index -1 or 100 for 100 lockers) gets you in trouble
pseudo
Index:   0    1    2    3    4
       ┌────┬────┬────┬────┬────┐
Values │ 10  │ 20  │ 30  │ 40  │ 50 │
       └────┴────┴────┴────┴────┘
Length: 5

2. Array Declaration and Creation

2.1 Two-Step Process

In Java, arrays are objects on the heap. Creating them has two steps:
java
int[] numbers;           // 1. DECLARE: reference variable (on stack)
numbers = new int[5];    // 2. CREATE: array object (on heap)
Or combined:
java
int[] numbers = new int[5];  // All elements default to 0

2.2 Declaration Styles

java
int[] numbers;    // Preferred style — type brackets with type
int numbers[];    // C-style — works but less readable
int []numbers;    // Legal but unusual
Recommended: Always put [] next to the type (int[]).

2.3 Initialization with Literals

java
int[] numbers = {10, 20, 30, 40, 50};          // Size inferred: 5
String[] names = {"Alice", "Bob", "Charlie"};   // Size inferred: 3
This shorthand can only be used in the declaration line:
java
int[] numbers;
numbers = {10, 20, 30};  // Compile error!
Use new for re-assignment:
java
int[] numbers;
numbers = new int[]{10, 20, 30};  // OK

2.4 Default Values

When created with new, array elements get default values:
TypeDefault Value
byte, short, int, long0
float, double0.0
char'\u0000' (null char)
booleanfalse
Reference types (String, Object)null

3. Accessing Array Elements

3.1 Indexing

java
int[] numbers = new int[5];
numbers[0] = 10;    // First element (index 0)
numbers[1] = 20;    // Second element
numbers[4] = 50;    // Last element (index length-1)
int x = numbers[2]; // Read element

3.2 The length Property

java
int[] arr = {10, 20, 30, 40, 50};
System.out.println(arr.length);  // 5 — note: no parentheses!
length is a field (not a method like String.length()).

3.3 Iterating Over Arrays

Using indexed for loop:
java
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
    System.out.println("Index " + i + ": " + numbers[i]);
}
Using enhanced for-each loop:
java
for (int num : numbers) {
    System.out.println(num);
}

4. Arrays Are Objects — Reference Semantics

java
int[] a = {1, 2, 3};
int[] b = a;        // b references the SAME array
b[0] = 99;
System.out.println(a[0]);  // 99 — a and b share the same array!
(Diagram) To copy an array:
java
int[] original = {1, 2, 3};
int[] copy = original.clone();              // Method 1: clone()
int[] copy2 = Arrays.copyOf(original, 3);   // Method 2: Arrays.copyOf
int[] copy3 = new int[3];
System.arraycopy(original, 0, copy3, 0, 3); // Method 3: System.arraycopy

5. Multi-Dimensional Arrays

5.1 Rectangular Arrays (Regular)

java
int[][] matrix = new int[3][4];  // 3 rows × 4 columns
matrix[0][0] = 1;   // Row 0, Column 0
matrix[2][3] = 12;  // Last row, last column
Initialization:
java
int[][] matrix = {
    {1, 2, 3, 4},     // Row 0
    {5, 6, 7, 8},     // Row 1
    {9, 10, 11, 12}   // Row 2
};
Iteration (nested loops):
java
for (int i = 0; i < matrix.length; i++) {        // Rows
    for (int j = 0; j < matrix[i].length; j++) { // Columns
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
}

5.2 Ragged Arrays (Irregular)

Each row can have a different length:
java
int[][] ragged = new int[3][];
ragged[0] = new int[5];  // Row 0: 5 columns
ragged[1] = new int[3];  // Row 1: 3 columns
ragged[2] = new int[7];  // Row 2: 7 columns
(Diagram)

6. Variable-Length Arguments (Varargs)

Varargs allow a method to accept a variable number of arguments:
java
public static int sum(int... numbers) {  // ... means varargs
    int total = 0;
    for (int n : numbers) {
        total += n;
    }
    return total;
}
// Usage
System.out.println(sum(1, 2));           // 3
System.out.println(sum(1, 2, 3, 4, 5)); // 15
System.out.println(sum());               // 0 (zero arguments is OK)
Rules:
  • Only one varargs parameter per method
  • It must be the last parameter
  • Inside the method, it's treated as an array
java
public static void printList(String prefix, String... items) {
    for (String item : items) {
        System.out.println(prefix + " " + item);
    }
}

7. java.util.Arrays Utility Class

MethodDescriptionExample
sort(arr)Sorts array in ascending orderArrays.sort(numbers)
binarySearch(arr, key)Searches sorted array (returns index)Arrays.binarySearch(arr, 42)
fill(arr, value)Fills array with a valueArrays.fill(arr, 0)
copyOf(arr, length)Copies array (new length)Arrays.copyOf(arr, 10)
equals(arr1, arr2)Checks element-by-element equalityArrays.equals(a, b)
toString(arr)Returns readable representationArrays.toString(arr)
deepToString(arr)For multi-dimensional arraysArrays.deepToString(matrix)
Examples:
java
int[] numbers = {42, 7, 15, 3, 99};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));  // [3, 7, 15, 42, 99]
int index = Arrays.binarySearch(numbers, 42);
System.out.println(index);  // 3 (0-based index)
int[] copy = Arrays.copyOf(numbers, 7);  // Extends with zeros
System.out.println(Arrays.toString(copy));  // [3, 7, 15, 42, 99, 0, 0]

8. Java vs Python: Arrays

FeatureJavaPython
TypeFixed-type (all elements same type)Dynamic (can mix types)
SizeFixed after creationDynamic (list grows/shrinks)
Syntaxint[] arr = new int[5];arr = [0] * 5 or arr = []
Lengtharr.length (field)len(arr) (function)
SlicingArrays.copyOfRange(arr, 1, 4)arr[1:4]
ResizingNot possible (new array needed)arr.append(), arr.pop()
Default values0, 0.0, false, nullNothing (list created empty)
Multi-dimensionalint[][] (array of arrays)Nested lists
Utilityjava.util.ArraysBuilt-in list methods

9. Common Pitfalls

Pitfall 1: ArrayIndexOutOfBoundsException

java
int[] arr = {1, 2, 3};
System.out.println(arr[3]);  // Index 3 out of bounds for length 3
Why: Valid indices are 0, 1, 2 (length-1). Index 3 is beyond the array. Fix: Always check index >= 0 && index < arr.length.

Pitfall 2: Confusing length with length()

java
int[] arr = {1, 2, 3};
String s = "Hello";
System.out.println(arr.length());  // Compile error! length is a field
System.out.println(s.length);      // Compile error! length() is a method
Why: Arrays use length (field), Strings use length() (method). Fix: Remember: arr.length (no parens), str.length() (with parens).

Pitfall 3: Treating == on Arrays as Content Comparison

java
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(a == b);         // false — different references
System.out.println(a.equals(b));    // false — arrays don't override equals()
System.out.println(Arrays.equals(a, b));  // true — element-by-element
Why: Arrays inherit equals() from Object, which compares references. Fix: Use Arrays.equals().

Pitfall 4: Assuming Default Values for Local Array Variables

java
int[] arr;
System.out.println(arr[0]);  // Compile error: arr not initialized!
Why: Local variables (including array references) must be initialized before use. Fix: int[] arr = new int[5]; or int[] arr = {1, 2, 3};

Pitfall 5: Modifying Array Through For-Each

java
int[] arr = {1, 2, 3};
for (int x : arr) {
    x = 99;  // Only changes local variable x, NOT arr[0], arr[1], arr[2]
}
System.out.println(Arrays.toString(arr));  // [1, 2, 3]
Why: For-each creates a copy of each element for primitives. Fix: Use indexed for loop to modify elements.

10. Practice Questions

Q1: What is the output?
java
int[] arr = new int[5];
arr[0] = 10;
arr[2] = 30;
for (int i = 0; i < arr.length; i++) {
    System.out.print(arr[i] + " ");
}
Answer: 10 0 30 0 0
The array is initialized with default values (0 for int). Only indices 0 and 2 are explicitly set; indices 1, 3, 4 retain the default 0. Q2: What happens with this code?
java
int[] arr = {1, 2, 3, 4, 5};
System.out.println(arr[-1]);
Answer: ArrayIndexOutOfBoundsException at runtime. Java does not support negative indexing (unlike Python). Valid indices are 0 to arr.length - 1. Q3: Write a method that reverses an array in place.
Answer:
java
public static void reverse(int[] arr) {
    int left = 0;
    int right = arr.length - 1;
    while (left < right) {
        int temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
        left++;
        right--;
    }
}

// Usage:
int[] nums = {1, 2, 3, 4, 5};
reverse(nums);
System.out.println(Arrays.toString(nums));  // [5, 4, 3, 2, 1]
Q4: What is the output?
java
int[][] grid = new int[2][];
grid[0] = new int[]{1, 2};
grid[1] = new int[]{3, 4, 5};
System.out.println(grid[0].length);
System.out.println(grid[1].length);
Answer: 2 then 3
This is a ragged array. Row 0 has length 2, row 1 has length 3. grid.length would be 2 (two rows). Q5: Fix this code to copy array content correctly
java
int[] a = {1, 2, 3};
int[] b = a;  // Bug: b references same array
b[0] = 99;
Answer: Use one of these copying methods:
java
int[] b = a.clone();                         // Method 1
int[] b = Arrays.copyOf(a, a.length);        // Method 2
int[] b = new int[a.length];                 // Method 3
System.arraycopy(a, 0, b, 0, a.length);
Now b[0] = 99; doesn't affect a. Q6: What does varargs allow you to do?
Answer: Varargs (type... name) allows a method to accept zero or more arguments of that type, packed into an array inside the method:
java
public static double average(double... values) {
    if (values.length == 0) return 0;
    double sum = 0;
    for (double v : values) sum += v;
    return sum / values.length;
}

System.out.println(average(1, 2, 3));     // 2.0
System.out.println(average());             // 0.0
System.out.println(average(5.0, 10.0));   // 7.5
Q7: What is the output of this search?
java
int[] arr = {10, 20, 30, 40, 50};
int index = Arrays.binarySearch(arr, 25);
System.out.println(index);
Answer: A negative number, specifically -3 (the insertion point is index 2, returned as -(insertion_point) - 1 = -(2) - 1 = -3).
binarySearch requires a SORTED array (this one is). For a missing element, it returns -(insertion_point) - 1 where insertion_point is where the element would be inserted to maintain sorted order. Q8: Write a method to find the maximum value in an int array.
Answer:
java
public static int findMax(int[] arr) {
    if (arr == null || arr.length == 0) {
        throw new IllegalArgumentException("Array cannot be null or empty");
    }
    int max = arr[0];
    for (int i = 1; i < arr.length; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}
Q9: What does Arrays.deepToString() do?
Answer: It converts multi-dimensional arrays to a readable string, showing nested content recursively:
java
int[][] matrix = {{1, 2}, {3, 4}};
System.out.println(Arrays.toString(matrix));      // [[I@..., [I@...] (junk!)
System.out.println(Arrays.deepToString(matrix));  // [1, 2], [3, 4](/viewer?path=1, 2], [3, 4)
Use deepToString for nested arrays; toString only shows reference addresses for the top-level. Q10: What is the output?
java
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(a.equals(b));
System.out.println(Arrays.equals(a, b));
Answer: false then true
  • a.equals(b) uses Object's equals, which compares references (not content) → false
  • Arrays.equals(a, b) compares elements one by one → true

📐 Key Concepts

ConceptSyntaxExample
Declarationtype[] nameint[] arr
Creationnew type[size]new int[10]
Literal{val1, val2, ...}{1, 2, 3}
Lengtharr.lengtharr.length
Accessarr[index]arr[0]
2D creationnew type[rows][cols]new int[3][4]
Varargstype... nameint... numbers
CopyArrays.copyOf(arr, newLen)Arrays.copyOf(arr, 5)

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.