Arrays and Strings
Use fixed-length arrays and the immutable String type, and accumulate text with StringBuilder.
Why it matters
Start from the concept, not the syntax
Meet a concrete situation where this idea earns its place, then state the boundary it guards.
Almost every program stores groups of values and handles text. Arrays give you fixed-length ordered storage; String and StringBuilder show two opposite strategies for data that changes—copying versus mutating—and choosing between them decides performance as well as clarity.
By the end of this chapter
Treating String as mutable and comparing it with == produces code that compiles but behaves wrong only for some inputs.
- Array bounds
- String immutability
- StringBuilder
Mechanism
How Java expresses the concept
Walk the actual types, rules, and runtime behavior involved—the same behavior described in the Java Language Specification.
The mental model
An array is a fixed-length, zero-indexed container. `int[] a = new int[3]` allocates three zeros; `int[] b = {1, 2, 3}` is the literal form. Length is `a.length` (a field, not a method). Multi-dimensional arrays are arrays of arrays, so each row can have a different length.
`String` is immutable: methods like `substring` or `toUpperCase` return a new `String` and leave the original untouched. Use an explicit `Charset` when converting between text and bytes. Use `==` to compare references, never content; use `equals` for content and `equalsIgnoreCase` when case does not matter.
Because concatenation in a loop builds many temporary strings, use `StringBuilder` (or `StringBuffer` when shared across threads) to accumulate text efficiently. `StringBuilder.append` mutates the buffer and `toString` produces the final `String`.
Common work: `charAt`, `length`, `substring`, `indexOf`, `split` (takes a regular expression), and `strip` for trimming whitespace. Prefer `strip` over the older `trim` because it understands Unicode spaces.
Concept map
Inspect the building blocks as a whole
Use the map as a structural reference; it shows the pieces and their relationships, not an execution sequence.
Core Java
Arrays, strings, and builders
Arrays are fixed-length containers of one type; String is an immutable sequence of characters. Its internal representation is a JVM implementation detail, not a language guarantee.
- 01Fixed-length arrays
- 02Jagged 2D arrays
- 03String immutability
- 04equals not ==
- 05StringBuilder
- 06split takes a regex
Implementation
Encode the smallest runnable example
Write and run the code, then observe the behavior you just predicted with a real Java program.
Runnable snippet path
Predict, run, and change each example
Build text with StringBuilder
Appending in a loop avoids creating a new String each time.
public class Csv {
static String join(String[] values) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < values.length; i++) {
if (i > 0) sb.append(",");
sb.append(values[i]);
}
return sb.toString();
}
}Remember
Use equals for String content; == compares object identity and will mislead you.
Change one input, predict the result, then compile or test it before continuing.
Compare strings correctly
Content comparison must use equals, not the reference operator.
public class Compare {
public static void main(String[] args) {
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
}
}Remember
Interning can make == true for literals; never rely on that for program logic.
Expected output
false true
Watch out
Break it on purpose, then repair the right layer
Predict the symptom before running the failure case, and close with the completion checklist.
Deliberate failure
Break
Compare two equal strings with == instead of equals
Observe
The check is false for content-equal strings built separately
Repair
Use equals for content comparison and treat String as immutable, so concatenation returns new objects
Why it matters
Use equals for content comparison and treat String as immutable, so concatenation returns new objects
Completion checklist
- Index arrays within bounds
- Use equals for string content
- Accumulate text with StringBuilder
Go deeper
Official references
The primary sources behind this chapter. Every claim above stays consistent with them.