Skip to main content

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.

L1

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.
  • length is a final field, not a method. Valid indexes are 0 .. length - 1. Out of range throws ArrayIndexOutOfBoundsException.
  • 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.
IdeaMeaningReal-life mapping
NameOne label for many valuesWeek temperatures
IndexPosition of one elementDay 0 = Monday
ElementValue at that index32 C on Monday
lengthHow many slots7 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).

Java 1D, 2D, and jagged arrays infographic: linear list, rectangular matrix, and uneven rows, with syntax, length fields, comparison table, and real-life analogies.
Java arrays — 1D for a list, 2D for a table, jagged when each row has its own length
  • 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: length is a field; print with Arrays.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 arrayWith 1D arrayBenefit
int m0, m1, m2, m3, m4;int[] marks = new int[5];One name, easy loops
Repeat print 5 timesfor (int i = 0; i < marks.length; i++)Scales to N students
Hard to find maxScan marks[i]Same code for any size
Pass many argsPass the arrayCleaner 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]; or int[] a = {80, 70, 90, 60, 85};. C-style int a[] is legal but less common in Java.
  • Declaration does not allocate: int[] a; is null until new or an initializer runs.
  • After new int[n], numbers default to 0, boolean to false, references to null.
  • Real-life examples: student marks, daily temperatures, playlist durations, monthly expenses.
Indexmarks[i]Real-life meaning
080Student A score
170Student B score
290Student C score
360Student D score
485Student 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.length is rows; m[i].length is 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.
PartMeaningReal-life mapping
seats[r][c]One cell in the gridSeat in row r, column c
seats.lengthHow many rowsCinema rows
seats[r].lengthSeats in that rowColumns
Nested forVisit every cellCheck 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][]; then j[0] = new int[2];.
  • Always use j[i].length for the inner loop — do not assume every row matches j[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.
Point1D2D rectangularJagged
ShapeSingle listTable / gridRows of mixed length
Indexesa[i]a[r][c]a[r][c] with varying a[r].length
Createnew int[n]new int[R][C]new int[R][] then each row
Typical loopOne forNested forNested for using a[r].length
Real-lifeMarks list, week tempsSeats, marks sheetTriangle, uneven coaches

java.util.Arrays helpers

  • println(a) prints type@hash, not the contents. Use Arrays.toString(a) for 1D and Arrays.deepToString(m) for 2D/jagged.
  • Arrays.sort, copyOf, fill, equals / deepEquals, and binarySearch (array must already be sorted).
NeedUse
Print contentsArrays.toString(a) / Arrays.deepToString(m)
SortArrays.sort(a)
CopyArrays.copyOf, System.arraycopy, a.clone() (shallow)
Fill / searchArrays.fill, Arrays.binarySearch (must be sorted)
CompareArrays.equals / Arrays.deepEquals
L2

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.
  • null row: int[][] m = new int[3][]; leaves m[0] as null until you assign new int[k]. Using m[0].length then throws NullPointerException.
  • There is no sizeof in Java. Ask a.length and Integer.BYTES if 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 an Object[]), which can throw ArrayStoreException if you store the wrong type. Generics were designed to avoid this.
  • Arrays.sort on 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 ArrayList or Arrays.copyOf to 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.length and c < a[r].length. <= is the classic ArrayIndexOutOfBoundsException.
  • Check a.length == 0 before reading a[0] for min/max.
  • new int[]{1, 2, 3} is an anonymous array — useful when passing a list of values to a method.
L3

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.

L4

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));
    }
}
L5

Problem Solving Tricks

  • Always loop i < a.length — i <= a.length throws ArrayIndexOutOfBoundsException.
  • Check length == 0 before reading a[0] for min/max.
  • Print with Arrays.toString (1D) or Arrays.deepToString (2D/jagged), never println(a).
  • For jagged / 2D, inner bound is a[r].length, not a hardcoded column count.
  • System.arraycopy is native and fast for bulk copies.
  • clone() of a 2D array is shallow — row arrays are shared.
  • Prefer ArrayList when the size changes; keep raw arrays for tight numeric loops.
  • Arrays.binarySearch is undefined (wrong answer) if the array is not sorted.
  • int[] a; is null until new — a NPE is not a bounds exception.
  • After new int[R][], assign every row before you read m[r][c].
L6

Practice Programs List

  1. Reverse a 1D array in place with two indexes.
  2. Find the second-largest distinct element in a 1D array.
  3. Rotate a 1D array right by k steps using reversal.
  4. Print a 2D marks sheet and each student’s total.
  5. Count free cinema seats (1) in a 2D grid of 0/1.
  6. Build a jagged triangle: row i has i+1 cells filled with 1..i+1.
  7. Sort a copy of an array without changing the original (Arrays.copyOf then sort).
  8. Demonstrate ArrayIndexOutOfBoundsException with a comment, then fix the bound.
  9. Print a jagged array with nested loops using each row’s length.
  10. Show that clone() of int[][] shares inner rows (change b[0][0] and print a).
  11. Fill a 2D array with Arrays.fill on each row.
  12. Search a sorted 1D array with Arrays.binarySearch and explain a negative result.