🎓
Real-world scenario
VidyaPath — Priya's exam-score pipeline (Bangalore)
VidyaPath is a Bangalore-based ed-tech platform that runs adaptive entrance-exam prep for 40,000 students. Priya, a backend engineer, needs to store a student's five most-recent mock-test transactions, display quarterly revenue per branch in a grid, and sort thousands of scores to quickly find where a student ranks. Her tool of choice: plain Java arrays — no generics needed yet.

📦 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.

Key vocabulary
  • int[] scores = new int[6] — declare then allocate. All elements initialise to 0.
  • 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].
TypeDefault valueExample 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.

javac Arrays1D.java && java Arrays1D
Arrays1D.java verified output below
stdout
Transactions : 5 Net balance : ₹13750.00 Largest credit: ₹8750.00 All entries : 4500 -1200 8750 -300 2000
The for-each loop (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).

javac Arrays2D.java && java Arrays2D
Arrays2D.java verified output below
stdout
Branch Q1 Q2 Q3 Q4 Total -------------------------------------------------- Mumbai 42 55 61 70 228 L Bangalore 38 44 50 58 190 L Nairobi 29 33 40 47 149 L Mumbai quarters sorted: [42, 55, 61, 70]
Why copy before sorting?

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.

javac ArraysUtils.java && java ArraysUtils
ArraysUtils.java verified output below
stdout
Sorted scores : [580, 640, 690, 720, 755, 810] Index of 720 : 3 Filled array : [-1, -1, -1, -1] Top 3 scores : [720, 755, 810]

📋 Arrays method quick-reference

MethodWhat it doesMutates original?
Arrays.sort(arr)Sorts in ascending orderYes
Arrays.toString(arr)Returns "[a, b, c]" stringNo
Arrays.binarySearch(arr, key)Returns index of key (array must be sorted)No
Arrays.fill(arr, val)Sets every element to valYes
Arrays.copyOf(arr, len)New array, copies first len elementsNo
Arrays.copyOfRange(arr, from, to)New array, copies [from, to)No
Arrays.equals(a, b)True if same length and all elements equalNo

🧠 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.

// Stack // Heap scores ──────────► [ 580 | 640 | 690 | 720 | 755 | 810 ] [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] top3 ──────────► [ 720 | 755 | 810 ] ← new object from copyOfRange // If you had written: int[] top3 = scores; // top3 would point at the SAME array — no copy made.
Always use Arrays.copyOf() or Arrays.copyOfRange() when you want an independent copy to sort or modify without affecting the original.

⚠️ Common mistakes

length() on an array
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.
ArrayIndexOutOfBoundsException
Accessing 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.
Sorting the source, not a copy
Calling Arrays.sort(revenue[0]) scrambles the original quarterly row. Always Arrays.copyOf() first if you need both the sorted and the original order.
binarySearch on unsorted data
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

Question 1 of 5
What is the default value of every element when you declare int[] arr = new int[5]?
Question 2 of 5
If scores has 6 elements, what index holds the last element?
Question 3 of 5
Which precondition must be met before calling Arrays.binarySearch(arr, key)?
Question 4 of 5
You write int[] b = a. What happens to b when you later call Arrays.sort(a)?
Question 5 of 5
Which statement extracts the last three elements of int[] scores (length 6) into a new array?
0/5

🎤 Interview Q&A

EasyWhat is the default value of an 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++.

EasyHow do you get the length of an array in Java?
+

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.

MediumWhy is a Java 2D array described as "an array of arrays"?
+

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.

MediumWhen would you choose 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.

HardWhat does 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 ArrayList when you need dynamic resizing.
  • arr.length is a field — no parentheses. Valid indices run 0 to arr.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 = a copies 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).
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

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 →