Board Formulas
β˜• JavaπŸ“… Day 8

Arrays in Java

Declare, initialize and access single-dimensional and 2D arrays in Java.

🎯

Learning objectives

  • β†’Declare and initialize arrays two ways
  • β†’Access, modify and iterate array elements
  • β†’Work with 2D arrays (matrices)

πŸ’‘ Key points

  • Array = fixed-size, ordered collection of same-type elements.
  • Zero-indexed: valid indices 0 to length - 1.
  • arr.length is a field (no parentheses), unlike String's length().
  • Once created, size cannot change. For dynamic sizing use ArrayList.

πŸ’» Code examples(4)

#1Declare and initialize
java
int[] a = new int[5];              // {0, 0, 0, 0, 0}
int[] b = {10, 20, 30, 40, 50};    // literal
int[] c = new int[]{1, 2, 3};      // long form

String[] names = {"Amit", "Priya", "Ravi"};
new int[5] creates 5 slots initialized to 0. Literals infer size from list.
#2Access and modify
java
int[] marks = {85, 90, 78};
System.out.println(marks[0]);   // 85
marks[2] = 95;                  // update
System.out.println(marks.length); // 3
Reading marks[3] throws ArrayIndexOutOfBoundsException β€” always index < length.
#3Iterate β€” two ways
java
int[] arr = {5, 10, 15};

// index-based (need i for position)
for (int i = 0; i < arr.length; i++) {
    System.out.println(i + ": " + arr[i]);
}

// for-each (cleaner when index not needed)
for (int x : arr) {
    System.out.println(x);
}
Prefer for-each unless you need the index or want to modify elements by index.
#42D array (matrix)
java
int[][] grid = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9},
};
System.out.println(grid[1][2]);   // 6

for (int[] row : grid) {
    for (int val : row) {
        System.out.print(val + " ");
    }
    System.out.println();
}
int[][] = array of arrays. grid[row][col] to access. Rows can even have different lengths (jagged array).

🎯 Practice

Q1. What is the default value of int[] arr = new int[3]?+

All slots default to 0. Boolean arrays default to false, object arrays to null.

Q2. Find the largest element in int[] nums = {3, 8, 1, 12, 5}.+

int max = nums[0]; for (int n : nums) if (n > max) max = n; // max = 12

Q3. Why is int[] length a field but String's length() a method?+

Arrays are special language constructs with length exposed directly. String is a class β€” length() is a proper method.

πŸ“ Notes

Common operations

// sum
int sum = 0;
for (int x : arr) sum += x;

// reverse in place
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
    int t = arr[i]; arr[i] = arr[j]; arr[j] = t;
}

// copy
int[] copy = arr.clone();

// sort
java.util.Arrays.sort(arr);

Array vs ArrayList

| | Array | ArrayList | |---|---|---| | Size | Fixed | Grows/shrinks | | Type | Any (primitive OK) | Objects only | | Methods | .length, indexing | rich API (add, remove, contains) | | Speed | Faster | Slightly slower |

Rule of thumb: fixed-size numeric data β†’ array. Everything else β†’ ArrayList.