4.1 Arrays — Objects on the Heap
A Java array is an object stored on the heap, even when it holds primitives. The reference lives on the stack; the contiguous element block lives on the heap along with a length field (a final field, not a method — contrast String.length()).
int[] a = new int[5]; // all elements default to 0
int[] b = {10, 20, 30}; // array literal
int c[] = new int[3]; // legal C-style, discouraged
Accessing a[5] on a 5-element array throws ArrayIndexOutOfBoundsException at runtime — Java always bounds-checks; there is no buffer overflow as in C.
4.2 2D & Jagged Arrays
Java has no true 2D arrays — a 2D array is an array of array references. This is why rows can have different lengths (jagged arrays):
int[][] matrix = new int[3][4]; // rectangular: 3 refs -> three int[4]
int[][] jagged = new int[3][]; // rows allocated separately
jagged[0] = new int[1];
jagged[1] = new int[2];
jagged[2] = new int[3];
for (int i = 0; i < jagged.length; i++) {
for (int j = 0; j < jagged[i].length; j++)
System.out.print(jagged[i][j] + " ");
System.out.println();
}
Memory picture in words: matrix points to an array of 3 references; each reference points to a separate int[4] object elsewhere on the heap — rows are not contiguous with each other.
Utility methods from java.util.Arrays: sort, binarySearch (requires sorted input), fill, copyOf, equals, deepToString (for 2D printing).
4.3 String — Immutable by Design
A String is an immutable object: every "modifying" method (concat, toUpperCase, replace…) returns a new String, leaving the original untouched. Benefits: safe sharing between threads, cacheable hash code (used by HashMap), security (file paths/URLs can't be mutated after checks), and enabling the string pool.
The String Constant Pool (SCP): a special region inside the heap where literals are interned.
String s1 = "java"; // goes to the pool
String s2 = "java"; // REUSES the same pool object
String s3 = new String("java"); // forces a NEW heap object outside the pool
System.out.println(s1 == s2); // true (same reference)
System.out.println(s1 == s3); // false (different objects)
System.out.println(s1.equals(s3)); // true (same characters)
System.out.println(s1 == s3.intern());// true (intern returns pool copy)
Golden rule: == compares references; equals() compares content. The number-one Java exam trap.
Compile-time constant folding: "ja" + "va" == "java" is true (folded into one literal), but s + "va" == "java" is false when s is a variable (computed at runtime, new object).
4.4 String vs StringBuilder vs StringBuffer
Concatenating inside a loop with + creates a new String every iteration — O(n²) total work. Use a mutable builder instead.
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutability | Immutable | Mutable | Mutable |
| Thread-safe | Yes (via immutability) | No | Yes (synchronized methods) |
| Speed | Slow for repeated edits | Fastest | Slower (locking overhead) |
| Introduced | JDK 1.0 | JDK 1.5 | JDK 1.0 |
| Use when | Fixed text, map keys | Single-threaded building | Shared mutable buffer (rare) |
Key builder methods: append, insert, delete, reverse, setCharAt, toString, capacity() (default 16, grows as 2×old+2).
4.5 High-Yield String Methods
length(), charAt(i), substring(begin, endExclusive), indexOf, equalsIgnoreCase, compareTo (lexicographic, returns <0/0/>0), trim/strip, split(regex), toCharArray, contains, startsWith/endsWith, String.join, valueOf, format, chars() (IntStream).
Trap: substring(2, 5) includes index 2 but excludes 5 — length is 3.
🎯 Exam Focus
- What is a jagged array? How does Java implement 2D arrays internally? Write a program to add two matrices.
- Explain the String Constant Pool with a diagram. Why is
s1 == s3false buts1.equals(s3)true when s3 usesnew String()? - Why are Strings immutable in Java? List four advantages of immutability.
- Compare String, StringBuilder and StringBuffer on mutability, thread-safety and performance.
- Write a program to check whether a string is a palindrome (a) using StringBuilder.reverse() and (b) using a two-pointer loop.
- Predict output:
"ja" + "va" == "java"vss + "va" == "java"— explain constant folding.