What to practice
- Trace String concatenation, escape sequences (\", \\, \n), and immutability.
- Evaluate nested calls to length(), substring(a, b), substring(a), and indexOf(str).
- Compare Strings accurately using equals() and compareTo().
Current CED topics: 1.15
Current learning objectives: 1.15.A, 1.15.B
1. Core Concept Instruction
Java String objects are immutable: String methods leave the original character sequence unchanged. substring returns the requested String value, but it need not allocate a new object; implementations may reuse an existing String. Immutability concerns the value, not whether every call creates a new identity. Characters in a String s are 0-indexed from 0 to s.length() - 1. (1) s.substring(from, to) returns the substring starting at index from (inclusive) up to index to (exclusive), which has exact length (to - from). Note that s.substring(i, i + 1) extracts the single-character String at index i, and s.substring(s.length()) returns the empty string "". (2) s.indexOf(target) returns the first index where target begins, or -1 if target does not occur in s. (3) Always compare Strings for content equality with s1.equals(s2) (never ==, which checks reference identity), and use s1.compareTo(s2) (< 0 if s1 precedes s2 lexicographically, 0 if equal, > 0 if s1 follows s2).
2. Worked Examples
Worked String Method Trace: substring, indexOf & compareTo
Let String word = "ALGORITHM"; (length 9, indices 0..8). Evaluate: (a) word.substring(2, 6), (b) word.substring(6), (c) word.indexOf("OR"), (d) word.indexOf("MATH"), and (e) "APPLE".compareTo("APRICOT").
- Step 1 (Write Index Header for "ALGORITHM"): 0:A, 1:L, 2:G, 3:O, 4:R, 5:I, 6:T, 7:H, 8:M.
- Step 2 (Evaluate Substrings): word.substring(2, 6) takes indices 2, 3, 4, 5 -> "GORI" (length 6 - 2 = 4). word.substring(6) takes indices 6 through 8 -> "THM".
- Step 3 (Evaluate indexOf Calls): "OR" begins at index 3, so word.indexOf("OR") returns 3. "MATH" is not found, so word.indexOf("MATH") returns -1.
- Step 4 (Evaluate compareTo): Comparing "APPLE" and "APRICOT" character by character, index 0 ('A') and index 1 ('P') match; at index 2, 'P' (ASCII 80) < 'R' (ASCII 82), so "APPLE".compareTo("APRICOT") returns a negative integer (-2 < 0).
Result:
String Concatenation Order, Immutability & Single-Argument substring(from)
Trace the exact value of tag after executing:
String raw = "AP-CSA-2027";
String part = raw.substring(3, 6);
String tail = raw.substring(7);
String tag = part + "-" + (2 + 5) + tail;
- Step 1 (Extract substrings): raw.substring(3, 6) extracts indices 3..5 ("CSA"); raw.substring(7) extracts from index 7 to the end ("2027").
- Step 2 (Evaluate parenthesized addition before concatenation): (2 + 5) evaluates to int 7 first, then concatenates to produce "CSA-72027".
Result: tag = "CSA-72027" (while raw remains unchanged as "AP-CSA-2027")