Skip to content

Lesson 01 · Arrays

Objectives

After this lesson you will be able to:

  • Declare and initialize one- and multi-dimensional arrays.
  • Use the Arrays utility (sort, binarySearch, equals, toString, fill, copyOf).
  • Avoid the array covariance trap (ArrayStoreException).

Declaring and initializing

An array is a fixed-length, ordered container of one type. Its length is a field, not a method.

java
int[] a = new int[3];            // {0, 0, 0} — default values
int[] b = {1, 2, 3};             // array initializer (only at declaration)
int[] c = new int[]{1, 2, 3};    // anonymous array form (usable anywhere)
a.length;                        // 3 (a field)

Exam trap

int[] b = {1,2,3}; works only in a declaration. To create an array inline elsewhere (e.g. a method argument) use new int[]{...}. The brackets may sit on the type or the name: int[] x and int x[] both compile; in int[] x, y; both x and y are arrays.

Multidimensional and jagged arrays

Java has arrays of arrays, so rows can have different lengths (jagged).

java
int[][] grid = new int[2][3];        // 2 rows, 3 cols, all 0
int[][] jagged = { {1}, {2, 3, 4} }; // rows of length 1 and 3
jagged[1][2];                        // 4
int[][] partial = new int[2][];      // rows are null until assigned

The Arrays utility

java.util.Arrays has the static helpers the exam tests:

java
int[] a = {3, 1, 2};
Arrays.sort(a);                       // {1, 2, 3} — sorts in place
Arrays.binarySearch(a, 2);            // 1 — array MUST be sorted first
Arrays.toString(a);                   // "[1, 2, 3]"  (plain toString gives a hash)
Arrays.equals(a, new int[]{1,2,3});   // true — element-wise
Arrays.fill(a, 0);                    // {0, 0, 0}
int[] copy = Arrays.copyOf(a, 5);     // grows, padding with 0
Arrays.deepToString(grid);            // for nested arrays

Gotcha

array.equals(other) and array.toString() use Object identity/hash — not contents. Use Arrays.equals/Arrays.toString (and deepEquals/deepToString for nested arrays).

Array covariance

Arrays are covariant: String[] is a Object[]. That's convenient but unsound — storing the wrong type compiles and throws ArrayStoreException at runtime.

java
Object[] arr = new String[2];   // legal — covariance
arr[0] = "ok";
arr[1] = 42;                    // ArrayStoreException at runtime!

SDET note

Generics (next lesson) are invariant precisely to catch this at compile time. Prefer a List<String> over a String[] when you want the compiler — not a runtime crash — to reject a wrong element type.

Key Takeaways

  • Arrays are fixed-length; length is a field. {…} init works only in a declaration; use new int[]{…} elsewhere.
  • Multidimensional arrays are arrays of arrays and may be jagged; inner rows can be null.
  • Use Arrays.* for sort/binarySearch (needs sorted input)/equals/toString/copyOf; plain equals/toString on an array are identity-based.
  • Arrays are covariant, so a wrong-type store throws ArrayStoreException at runtime — generics fix this at compile time.

Lesson Quiz

Lesson Quiz · Arrays0 / 5
  1. What happens at runtime?

    Object[] arr = new String[2];
    arr[0] = 42;
    • AStores 42
    • BCompile error
    • CArrayStoreException
    • DNullPointerException
  2. Which is required before Arrays.binarySearch?

    • AThe array must be reversed
    • BThe array must be sorted
    • CNothing
    • DIt must be an Integer[]
  3. What does new int[3] contain?

    • Anull, null, null
    • B0, 0, 0
    • Cgarbage
    • Dempty
  4. In int[] x, y; what are x and y?

    • Ax is an array, y is an int
    • BBoth are arrays
    • CBoth are ints
    • DCompile error
  5. What does Arrays.toString(new int[]{1,2}) return?

    • A"[I@1b6d"
    • B"[1, 2]"
    • C"{1, 2}"
    • D"12"

Next: Generics. Run the matching code in labs/src/main/java/com/jse21/m05_collections/.