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. One-dimensional and multi-dimensional arrays, length, copying, and the Arrays helper class.
What is an array?
- An array is a fixed-length, ordered collection of the same type stored on the heap.
lengthis a field, not a method. - Declaration does not allocate:
int[] a;isnulluntilnew int[n]or an initializer runs. - Valid indexes are
0..length - 1. Out of range throwsArrayIndexOutOfBoundsException.
import java.util.Arrays;
public class ArrayBasics {
public static void main(String[] args) {
int[] a = {4, 1, 3};
System.out.println(a.length);
Arrays.sort(a);
System.out.println(Arrays.toString(a));
}
} Declaration styles and defaults
int[] ais the preferred type-suffix style;int a[]is legal C-style.- Numeric elements default to
0,booleantofalse, references tonullafternew Type[n]. new int[]{1, 2, 3}is an anonymous array expression — useful when passing to a method.
2D and jagged arrays
int[][] m = new int[2][3];is a matrix: 2 rows, 3 columns.m.lengthis rows;m[i].lengthis that row’s columns.- Java arrays of arrays can be jagged:
new int[3][]then each rownew int[differentSize].
| Need | Use |
|---|---|
| Print contents | Arrays.toString(a) / Arrays.deepToString(m) |
| Sort | Arrays.sort(a) — Dual-Pivot Quicksort for primitives |
| Copy | Arrays.copyOf, System.arraycopy, a.clone() (shallow) |
| Fill / search | Arrays.fill, Arrays.binarySearch (must be sorted) |
| Compare | Arrays.equals / Arrays.deepEquals |
Advanced — Arrays
Shallow clone, covariance, and complexity
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.
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.
Q4) 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.
Q5) 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.
Q6) How do you print an array?
Answer Not with println(a) — that prints type@hash. Use Arrays.toString or a loop.
Simple Programs
Sum, max, and 2D print
import java.util.Arrays;
public class ArrayPrograms {
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;
}
int[][] m = {{1, 2}, {3, 4, 5}};
System.out.println("sum=" + sum + " max=" + max);
System.out.println(Arrays.deepToString(m));
}
} Problem Solving Tricks
- Always check
length == 0before readinga[0]for min/max. System.arraycopyis native and fast for bulk copies.- Prefer
ArrayListwhen the size changes; keep raw arrays for tight numeric loops and interview “implement from scratch” questions. Arrays.binarySearchis undefined (wrong answer) if the array is not sorted.
Practice Programs List
- Reverse an array in place with two indexes.
- Find the second-largest distinct element.
- Rotate an array right by k steps using reversal.
- Build a jagged triangle: row i has i+1 zeros, then fill with 1..n.
- Sort a copy of an array without changing the original (
Arrays.copyOfthensort).