📦 What is an array?
An array is a fixed-size, ordered container of elements of the same type stored contiguously in memory. Once you create an array of length n, that length cannot change — you can only read or overwrite elements.
int[] scores = new int[6]— declare then allocate. All elements initialise to0.int[] scores = {720, 580, 810}— declare + initialise in one step (array literal).scores.length— field (not a method). No parentheses.- Index is zero-based: first element at
[0], last at[length - 1].
| Type | Default value | Example literal |
|---|---|---|
int[] | 0 | {10, 20, 30} |
double[] | 0.0 | {1.5, 2.5} |
boolean[] | false | {true, false, true} |
String[] | null | {"a", "b"} |
🔢 1D arrays — transaction ledger
Priya stores a student's five wallet credits and debits in a double[]. She iterates with both a classic index loop and an enhanced for-each to compute the running balance and largest credit.
for (double t : transactions)) is read-only — you can't change elements through the loop variable. Use an indexed loop when you need to write back.🗂️ 2D arrays — branch revenue grid
VidyaPath tracks quarterly revenue (in lakhs) per city branch. A 2D array is the natural fit: rows are branches, columns are quarters. Java's 2D array is actually an array of arrays — each row is a separate heap object, which means rows can even have different lengths (jagged arrays).
Arrays.sort() mutates the array in place. Sorting revenue[0] directly would destroy the original quarterly order. Arrays.copyOf() creates a fresh array so the source is untouched.
🛠️ The Arrays utility class
java.util.Arrays ships static helper methods that save you from writing common loops yourself. Import it at the top of your file and the full toolkit is available.
📋 Arrays method quick-reference
| Method | What it does | Mutates original? |
|---|---|---|
Arrays.sort(arr) | Sorts in ascending order | Yes |
Arrays.toString(arr) | Returns "[a, b, c]" string | No |
Arrays.binarySearch(arr, key) | Returns index of key (array must be sorted) | No |
Arrays.fill(arr, val) | Sets every element to val | Yes |
Arrays.copyOf(arr, len) | New array, copies first len elements | No |
Arrays.copyOfRange(arr, from, to) | New array, copies [from, to) | No |
Arrays.equals(a, b) | True if same length and all elements equal | No |
🧠 How arrays live in memory
An array variable on the stack holds a reference (pointer) to the array object on the heap. Assigning int[] b = a does NOT copy the data — both a and b point to the same heap block.
Arrays.copyOf() or Arrays.copyOfRange() when you want an independent copy to sort or modify without affecting the original.⚠️ Common mistakes
scores.length() won't compile. Arrays expose .length as a field, not a method. String uses .length(); List uses .size() — don't mix them up.arr[arr.length] crashes at runtime. The valid range is always 0 to arr.length - 1. Off-by-one errors in loop bounds are the #1 cause.Arrays.sort(revenue[0]) scrambles the original quarterly row. Always Arrays.copyOf() first if you need both the sorted and the original order.Arrays.binarySearch() returns a meaningless (or negative) index when the array is not sorted. Sort first, then search — or use a linear scan for unsorted arrays.🧠 Quick check
int[] arr = new int[5]?scores has 6 elements, what index holds the last element?Arrays.binarySearch(arr, key)?int[] b = a. What happens to b when you later call Arrays.sort(a)?int[] scores (length 6) into a new array?🎤 Interview Q&A
int array element in Java?0. Java guarantees that primitive arrays are zero-initialised: int[] → 0, double[] → 0.0, boolean[] → false. Object arrays default to null. This removes the undefined-memory bugs common in C/C++.
Use the .length field, not a method — so no parentheses: arr.length. Compare: String.length() is a method and List.size() is also a method. Only arrays use a bare field. Common mistake in interviews: writing arr.length() which is a compile error.
int[][] grid is actually a 1D array of int[] references. Each row is a separate heap object. Consequences: (1) rows can have different lengths (jagged arrays like int[][] tri = {{1}, {1,2}, {1,2,3}}), (2) you can reassign a row with grid[0] = new int[]{9,9,9}, and (3) copying the outer array does not copy the row arrays — it is a shallow copy.
Arrays.copyOf() over Arrays.copyOfRange()?copyOf(arr, newLen) always starts at index 0 and is convenient for truncating or padding: if newLen > arr.length the extra slots are zero-filled. copyOfRange(arr, from, to) lets you extract any sub-range. Use copyOf when you want a head slice or a resize; use copyOfRange for mid-section or tail slices.
Arrays.binarySearch() return when the key is not in the array?A negative value: -(insertionPoint) - 1. The insertion point is the index where the key would be inserted to keep the array sorted. For example, if binarySearch({580, 640, 720}, 700) runs, 700 would go at index 2, so the return is -(2) - 1 = -3. You can recover the insertion point with -(result) - 1. The -1 offset ensures that a return of 0 always means "found at index 0", not "not found at the start".
✅ Key takeaways
- Arrays are fixed-size; use
ArrayListwhen you need dynamic resizing. arr.lengthis a field — no parentheses. Valid indices run0toarr.length - 1.Arrays.sort()mutates in place. Copy first if you need both orders.Arrays.binarySearch()requires a sorted array or results are undefined.- Assigning
int[] b = acopies the reference, not the data — both variables see the same array. - A 2D array is an array of array references; rows can have different lengths (jagged arrays).
Ready for backend engineering?
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →