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. 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. length is a field, not a method.
  • Declaration does not allocate: int[] a; is null until new int[n] or an initializer runs.
  • Valid indexes are 0 .. length - 1. Out of range throws ArrayIndexOutOfBoundsException.
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[] a is the preferred type-suffix style; int a[] is legal C-style.
  • Numeric elements default to 0, boolean to false, references to null after new 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.length is rows; m[i].length is that row’s columns.
  • Java arrays of arrays can be jagged: new int[3][] then each row new int[differentSize].
NeedUse
Print contentsArrays.toString(a) / Arrays.deepToString(m)
SortArrays.sort(a) — Dual-Pivot Quicksort for primitives
CopyArrays.copyOf, System.arraycopy, a.clone() (shallow)
Fill / searchArrays.fill, Arrays.binarySearch (must be sorted)
CompareArrays.equals / Arrays.deepEquals
L2

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

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.

L4

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

Problem Solving Tricks

  • Always check length == 0 before reading a[0] for min/max.
  • System.arraycopy is native and fast for bulk copies.
  • Prefer ArrayList when the size changes; keep raw arrays for tight numeric loops and interview “implement from scratch” questions.
  • Arrays.binarySearch is undefined (wrong answer) if the array is not sorted.
L6

Practice Programs List

  1. Reverse an array in place with two indexes.
  2. Find the second-largest distinct element.
  3. Rotate an array right by k steps using reversal.
  4. Build a jagged triangle: row i has i+1 zeros, then fill with 1..n.
  5. Sort a copy of an array without changing the original (Arrays.copyOf then sort).