Arrays & Strings
Arrays
Complete lesson for Arrays using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Arrays
Section: Arrays & Strings. 1D, 2D, and jagged arrays — length, indexing, traversal, java.util.Arrays, and real-life examples.
What is an array?
- An array stores many values of the same type under one name. In Java the array object lives on the heap; the variable holds a reference.
lengthis a final field, not a method. Valid indexes are0..length - 1. Out of range throwsArrayIndexOutOfBoundsException.- 1D array: a single list — marks of 5 students, temperatures for 7 days.
- 2D rectangular array: a table — cinema seats (rows × columns), marks sheet.
- Jagged array: an array of arrays whose rows can have different lengths.
- Use the image below to see 1D, 2D, and jagged layouts side by side.
| Idea | Meaning | Real-life mapping |
|---|---|---|
| Name | One label for many values | Week temperatures |
| Index | Position of one element | Day 0 = Monday |
| Element | Value at that index | 32 C on Monday |
length | How many slots | 7 days in a week |
1D, 2D & jagged arrays — layout and uses
Arrays store many same-type values on the heap. The diagram below compares 1D (a list), 2D rectangular (a table), and jagged arrays (rows of different lengths).
- 1D: one index
a[i]— marks, ages, temperatures. - 2D: two indices
a[r][c]— seats, marks sheets; all rows same width. - Jagged:
new int[n][]then each row — triangle, uneven coaches. - Java:
lengthis a field; print withArrays.toString/deepToString.
Why we need 1D arrays
- Without arrays you invent many separate variables:
m0, m1, m2, m3, m4— hard to loop, search, or pass around. - A 1D array gives one name plus indexes so you can process a list with a single loop.
- Use 1D when data is a sequence of the same kind of value (one dimension is enough).
| Without 1D array | With 1D array | Benefit |
|---|---|---|
int m0, m1, m2, m3, m4; | int[] marks = new int[5]; | One name, easy loops |
| Repeat print 5 times | for (int i = 0; i < marks.length; i++) | Scales to N students |
| Hard to find max | Scan marks[i] | Same code for any size |
| Pass many args | Pass the array | Cleaner methods |
public class WhyOneD {
public static void main(String[] args) {
int[] marks = {80, 70, 90, 60, 85};
for (int i = 0; i < marks.length; i++) {
System.out.print(marks[i] + " ");
}
}
} 1D arrays
- Preferred syntax:
int[] a = new int[5];orint[] a = {80, 70, 90, 60, 85};. C-styleint a[]is legal but less common in Java. - Declaration does not allocate:
int[] a;isnulluntilnewor an initializer runs. - After
new int[n], numbers default to0,booleantofalse, references tonull. - Real-life examples: student marks, daily temperatures, playlist durations, monthly expenses.
| Index | marks[i] | Real-life meaning |
|---|---|---|
| 0 | 80 | Student A score |
| 1 | 70 | Student B score |
| 2 | 90 | Student C score |
| 3 | 60 | Student D score |
| 4 | 85 | Student E score |
public class OneDMarks {
public static void main(String[] args) {
int[] marks = {80, 70, 90, 60, 85};
for (int i = 0; i < marks.length; i++) {
System.out.println("Student " + (i + 1) + ": " + marks[i]);
}
System.out.println("length = " + marks.length);
}
} Why we need 2D arrays
- Some data is naturally a table: rows and columns together (student × subject, seat row × seat number).
- With only 1D you flatten awkwardly (
index = row * cols + col) or use many separate 1D arrays. - A 2D array keeps the table shape:
data[row][col]matches how people think about grids.
public class WhyTwoD {
public static void main(String[] args) {
int[][] marks = {
{80, 70, 90, 60},
{75, 85, 80, 70},
{90, 88, 92, 85}
};
System.out.println(marks[1][2]); // student 1, subject 2
}
} 2D rectangular arrays
int[][] m = new int[3][4];is a matrix: 3 rows, 4 columns.m.lengthis rows;m[i].lengthis that row’s columns (same for every row in a rectangle).- Access:
m[row][col]. Nested loops: outer = rows, inner = columns. - Real-life examples: cinema seating, class marks sheet, chess board, hotel floors × rooms, timetable.
| Part | Meaning | Real-life mapping |
|---|---|---|
seats[r][c] | One cell in the grid | Seat in row r, column c |
seats.length | How many rows | Cinema rows |
seats[r].length | Seats in that row | Columns |
Nested for | Visit every cell | Check all seats for booking |
public class CinemaSeats {
public static void main(String[] args) {
int[][] seats = {
{1, 1, 0, 1},
{1, 0, 0, 1},
{1, 1, 1, 0}
};
for (int r = 0; r < seats.length; r++) {
for (int c = 0; c < seats[r].length; c++) {
System.out.print(seats[r][c] == 1 ? "F " : "B ");
}
System.out.println();
}
}
} Jagged arrays
- A jagged array is an array of arrays whose rows have different lengths. Create the outer array first, then each row:
int[][] j = new int[3][];thenj[0] = new int[2];. - Always use
j[i].lengthfor the inner loop — do not assume every row matchesj[0].length. - Real-life examples: a triangle of students (row i has i+1 people), train coaches with different seat counts, Pascal’s triangle.
public class JaggedDemo {
public static void main(String[] args) {
int[][] j = new int[3][];
j[0] = new int[] {10, 20};
j[1] = new int[] {30, 40, 50, 60};
j[2] = new int[] {70, 80, 90};
for (int r = 0; r < j.length; r++) {
for (int c = 0; c < j[r].length; c++) {
System.out.print(j[r][c] + " ");
}
System.out.println();
}
}
} Differences between 1D, 2D, and jagged
- Pick 1D for a list, 2D when every row has the same width, jagged when row lengths differ.
| Point | 1D | 2D rectangular | Jagged |
|---|---|---|---|
| Shape | Single list | Table / grid | Rows of mixed length |
| Indexes | a[i] | a[r][c] | a[r][c] with varying a[r].length |
| Create | new int[n] | new int[R][C] | new int[R][] then each row |
| Typical loop | One for | Nested for | Nested for using a[r].length |
| Real-life | Marks list, week temps | Seats, marks sheet | Triangle, uneven coaches |
java.util.Arrays helpers
println(a)prints type@hash, not the contents. UseArrays.toString(a)for 1D andArrays.deepToString(m)for 2D/jagged.Arrays.sort,copyOf,fill,equals/deepEquals, andbinarySearch(array must already be sorted).
| Need | Use |
|---|---|
| Print contents | Arrays.toString(a) / Arrays.deepToString(m) |
| Sort | Arrays.sort(a) |
| Copy | Arrays.copyOf, System.arraycopy, a.clone() (shallow) |
| Fill / search | Arrays.fill, Arrays.binarySearch (must be sorted) |
| Compare | Arrays.equals / Arrays.deepEquals |
Advanced — Arrays
Heap layout: Java 2D is an array of references
- A 1D
int[]is one heap object whose cells sit together. The variable stores a reference, not the cells themselves. - A Java
int[][]is not one C-style row-major block. The outer array holds references to row arrays. That is why jagged rows are natural. nullrow:int[][] m = new int[3][];leavesm[0]asnulluntil you assignnew int[k]. Usingm[0].lengththen throwsNullPointerException.- There is no
sizeofin Java. Aska.lengthandInteger.BYTESif you need byte estimates.
Shallow clone, covariance, and growth
clone()on a 2D array copies the outer array only — inner rows are shared (shallow). Same for arrays of objects.- Arrays are covariant (
String[]is anObject[]), which can throwArrayStoreExceptionif you store the wrong type. Generics were designed to avoid this. Arrays.sorton primitives is Dual-Pivot Quicksort (average O(n log n)). On objects it is TimSort and is stable.- An array cannot grow. If you need resize, use
ArrayListorArrays.copyOfto a larger array.
import java.util.Arrays;
public class ShallowCopy {
public static void main(String[] args) {
int[][] a = {{1, 2}, {3, 4}};
int[][] b = a.clone();
b[0][0] = 99;
System.out.println(Arrays.deepToString(a)); // [[99, 2], [3, 4]]
}
} Traversal, bounds, and empty arrays
- Always loop
i < a.lengthandc < a[r].length.<=is the classicArrayIndexOutOfBoundsException. - Check
a.length == 0before readinga[0]for min/max. new int[]{1, 2, 3}is an anonymous array — useful when passing a list of values to a method.
Tricky Interview Points
Q1) Is length a method on arrays?
Answer No. Arrays expose a final field length. String uses length() and Collection uses size().
Q2) Where do arrays live?
Answer The array object is on the heap. The variable holds a reference. Primitives inside are stored in the array; object arrays store references.
Q3) What is a jagged array?
Answer An array of arrays whose rows have different lengths, because each row is its own array object. Create with new int[n][] then assign each row.
Q4) How is Java int[][] different from a C++ 2D array?
Answer Java stores an array of row references, so rows can have different lengths. C++ int m[R][C] is one contiguous row-major block.
Q5) Difference between clone() and Arrays.copyOf for object arrays?
Answer Both are shallow: they copy references, not deep-copy elements. copyOf can also change length.
Q6) Why can String[] be passed to a method that takes Object[]?
Answer Arrays are covariant. Inserting an Integer into that Object[] at runtime throws ArrayStoreException.
Q7) How do you print an array?
Answer Not with println(a) — that prints type@hash. Use Arrays.toString for 1D and Arrays.deepToString for 2D or jagged.
Q8) What are the default values after new int[5] and new boolean[2]?
Answer 0 for numeric types, false for boolean, null for reference types.
Q9) What happens if you use m[0].length after int[][] m = new int[3][]?
Answer NullPointerException, because each row is still null until you assign a 1D array.
Q10) Can an array grow after creation?
Answer No. The length is fixed. Use ArrayList, or Arrays.copyOf to a larger array and replace the reference.
Q11) Which indexes are valid for an array of length n?
Answer 0 through n-1. a[n] throws ArrayIndexOutOfBoundsException.
Q12) int[] a vs int a[] — which style is preferred?
Answer int[] a is the Java style (type on the left). int a[] is legal C-style leftover.
Simple Programs
1D — sum and max
public class SumMax {
public static void main(String[] args) {
int[] a = {5, 2, 9, 1};
int sum = 0, max = a[0];
for (int n : a) {
sum += n;
if (n > max) max = n;
}
System.out.println("sum=" + sum + " max=" + max);
}
} 2D — student totals
public class MarksSheet {
public static void main(String[] args) {
int[][] marks = {
{80, 70, 90, 60},
{75, 85, 80, 70},
{90, 88, 92, 85}
};
for (int s = 0; s < marks.length; s++) {
int total = 0;
for (int sub = 0; sub < marks[s].length; sub++) {
total += marks[s][sub];
}
System.out.println("Student " + (s + 1) + " total = " + total);
}
}
} Jagged — triangle rows
import java.util.Arrays;
public class JaggedTriangle {
public static void main(String[] args) {
int[][] t = new int[4][];
for (int i = 0; i < t.length; i++) {
t[i] = new int[i + 1];
for (int j = 0; j < t[i].length; j++) {
t[i][j] = j + 1;
}
}
System.out.println(Arrays.deepToString(t));
}
} Reverse 1D in place
import java.util.Arrays;
public class ReverseArray {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5};
int i = 0, j = a.length - 1;
while (i < j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
i++;
j--;
}
System.out.println(Arrays.toString(a));
}
} Copy then sort without changing original
import java.util.Arrays;
public class CopyThenSort {
public static void main(String[] args) {
int[] a = {4, 1, 3};
int[] b = Arrays.copyOf(a, a.length);
Arrays.sort(b);
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
}
} Problem Solving Tricks
- Always loop
i < a.length—i <= a.lengththrowsArrayIndexOutOfBoundsException. - Check
length == 0before readinga[0]for min/max. - Print with
Arrays.toString(1D) orArrays.deepToString(2D/jagged), neverprintln(a). - For jagged / 2D, inner bound is
a[r].length, not a hardcoded column count. System.arraycopyis native and fast for bulk copies.clone()of a 2D array is shallow — row arrays are shared.- Prefer
ArrayListwhen the size changes; keep raw arrays for tight numeric loops. Arrays.binarySearchis undefined (wrong answer) if the array is not sorted.int[] a;is null untilnew— a NPE is not a bounds exception.- After
new int[R][], assign every row before you readm[r][c].
Practice Programs List
- Reverse a 1D array in place with two indexes.
- Find the second-largest distinct element in a 1D array.
- Rotate a 1D array right by k steps using reversal.
- Print a 2D marks sheet and each student’s total.
- Count free cinema seats (
1) in a 2D grid of 0/1. - Build a jagged triangle: row i has i+1 cells filled with 1..i+1.
- Sort a copy of an array without changing the original (
Arrays.copyOfthensort). - Demonstrate
ArrayIndexOutOfBoundsExceptionwith a comment, then fix the bound. - Print a jagged array with nested loops using each row’s
length. - Show that
clone()ofint[][]shares inner rows (changeb[0][0]and printa). - Fill a 2D array with
Arrays.fillon each row. - Search a sorted 1D array with
Arrays.binarySearchand explain a negative result.