Study guide
1.4 Text Blocks, String Immutability, and StringBuilder APIs
Oracle Java SE 17 Developer Certified Professional 1Z0-829
Track your progress as you read
Finished sections get a check mark.
1 Introduction: The 1Z0-829 Exam
About the Java SE 17 Developer (1Z0-829) Exam
2 Chapter 1: Java Fundamentals & Language Basics
1.1 Primitive Types, Literals, Wrapper Classes, and Type Promotion/Casting 1.2 Local Variable Type Inference (`var`) Rules and Scoping 1.3 Operators, Precedence, Evaluation Order, and Short-Circuit Evaluation 1.4 Text Blocks, String Immutability, and StringBuilder APIs
3 Chapter 2: Program Flow & Decision Constructs
2.1 Conditional Branching with if/else and the Ternary Operator 2.2 Switch Statements and Switch Expressions 2.3 Iteration Constructs, Loop Control, and Branching Labels
4 Chapter 3: Object-Oriented Design & Class Mechanics
3.1 Class Declarations, Field/Method Signatures, and Access Modifiers 3.2 Constructors, Overloading, Initialization Order, and Garbage Collection 3.3 Inheritance, Method Overriding, Polymorphism, and `super`/`this` 3.4 Abstract Classes, Static Members, and Object Methods (`equals`, `hashCode`, `toString`)
5 Chapter 4: Advanced OOP: Interfaces, Records & Sealed Types
4.1 Interface Architecture: Default, Static, and Private Methods 4.2 Enumerations: Constants, Constructors, Methods, and Custom Bodies 4.3 Records: Canonical/Compact Constructors, Components, and Immutability 4.4 Sealed Classes and Interfaces: `permits`, Hierarchy Constraints, and Modifiers
6 Chapter 5: Pattern Matching & Nested Types
5.1 Pattern Matching for `instanceof` and Flow Scoping Mechanics 5.2 Nested Types: Member Inner, Static Nested, Local, and Anonymous Classes 5.3 Defensive Programming, Immutability Patterns, and Validation
7 Chapter 6: Generics, Collections & Arrays
6.1 Generic Classes, Interfaces, Methods, and Type Erasure 6.2 Bounded Type Parameters and Wildcards (PECS Rule) 6.3 Collections Framework: List, Set, Queue, and Deque APIs 6.4 The Map Interface, Sorting, Comparable, and Comparator 6.5 Arrays: Declaration, Initialization, Multidimensional Arrays, and the Arrays Utility Class
8 Chapter 7: Functional Programming & Lambda Expressions
7.1 Functional Interfaces and Lambda Syntax Rules 7.2 Standard Functional Interfaces in `java.util.function` 7.3 Method References: Static, Bound, Unbound, and Constructor References
9 Chapter 8: The Stream API
8.1 Stream Lifecycle: Creation, Pipeline Architecture, and Lazy Evaluation 8.2 Intermediate Stream Operations: Filtering, Mapping, Sorting, and Slicing 8.3 Terminal Stream Operations: Reduction, Matching, Finding, and Collecting 8.4 Primitive Streams (`IntStream`, `LongStream`, `DoubleStream`) and Numeric Statistics
10 Chapter 9: Advanced Streams & Collectors
9.1 The Optional Class: Safe Null Handling, Transformation, and Chaining 9.2 The Collectors API: Downstream Reductions, Grouping, and Partitioning 9.3 Parallel Streams: Fork/Join Pool, Spliterators, and Concurrency Pitfalls
11 Chapter 10: Exception Handling
10.1 The Java Exception Hierarchy: Checked vs. Unchecked Exceptions and Errors 10.2 Exception Constructs: `try-catch-finally`, Multi-Catch, and Rethrowing 10.3 Try-With-Resources, `AutoCloseable`, Suppressed Exceptions, and Custom Exceptions
12 Chapter 11: Date/Time API & Localization
11.1 Date and Time Core Types: `LocalDate`, `LocalTime`, `LocalDateTime` 11.2 Timestamps, Intervals, and Durations: `Instant`, `Period`, and `Duration` 11.3 Time Zones, Daylight Saving Time (DST) Offsets, and `ZonedDateTime` 11.4 Internationalization and Localization: `Locale`, `ResourceBundle`, and Formatters 11.5 Formatting and Parsing Messages, Numbers, Percentages, and Localized Dates
13 Chapter 12: Java Platform Module System (JPMS)
12.1 Module Architecture, `module-info.java`, and Module Paths 12.2 Module Directives: `requires`, `requires transitive`, `exports`, and Qualified Exports 12.3 Reflection, Deep Encapsulation, `opens`, and Open Modules 12.4 Services in JPMS (`uses`, `provides...with`), Migration Paths, and Tooling (`jlink`, `jdeps`) 12.5 Compiling and Packaging Code: Non-Modular JARs, Modular JARs, and Migration Strategies
14 Chapter 13: Concurrency & Multithreading
13.1 Thread Fundamentals, `Runnable`, `Callable`, and Thread Lifecycle 13.2 Memory Visibility, `volatile`, Intrinsic Locks, and Synchronization 13.3 The Concurrency Framework: `ExecutorService`, Thread Pools, and `Future` 13.4 Concurrent Collections, Atomic Variables, Explicit Locks, and `CompletableFuture`
15 Chapter 14: Java I/O and NIO.2
14.1 Classical I/O: Byte and Character Streams, Readers, Writers, and Buffering 14.2 Object Serialization, `Serializable`, `transient`, and `serialVersionUID` 14.3 NIO.2 Architecture: `Path`, `Paths`, and Basic `Files` Operations 14.4 Advanced NIO.2: Directory Walking, Streams (`Files.lines`, `walk`), and `WatchService`
16 Chapter 15: Accessing Databases with JDBC
15.1 JDBC Architecture, Drivers, `DriverManager`, and `DataSource` Connections 15.2 SQL Execution: `Statement`, `PreparedStatement`, and `CallableStatement` 15.3 `ResultSet` Navigation, Data Types, and Transaction Management (Commit, Rollback, Savepoints)
17 Chapter 16: Annotations & the Java Logging API
16.1 Standard Annotations: @Override, @FunctionalInterface, @Deprecated, @SuppressWarnings, and @SafeVarargs 16.2 Java Logging API Basics: Logger, Levels, Handlers, and Configuration
1.4 Text Blocks, String Immutability, and StringBuilder APIs
Key Takeaways Explain This Topic AI
Text blocks (standardized in Java 15 by JEP 378) begin with three double quotes (""") followed by optional whitespace and a mandatory line terminator; no content can appear on the opening delimiter line.
The compiler strips incidental indentation based on the leftmost non-whitespace character or the position of the closing """ delimiter; escape sequence \s preserves trailing spaces, while \ suppresses line breaks.
String instances are immutable and stored in the String Constant Pool when created via literals or intern(); string transformation methods return new instances and never alter the original string.
Java 11 through 17 introduced powerful String methods including strip(), isBlank(), lines(), repeat(), formatted(), indent(), and transform().
StringBuilder provides an unsynchronized, mutable character sequence with dynamic capacity; it does not override equals() or hashCode(), meaning equals() tests reference identity rather than character content.
Last updated: October 2026
Text Blocks, String Immutability, and StringBuilder APIs
String processing is central to Java development and exam assessments. Java SE 17 includes text blocks (standardized in Java 15 via JEP 378), modern String inspection and transformation methods added across Java 11–17, and high-performance in-place mutation using StringBuilder .
Text Blocks Syntax and Indentation Algorithms
A text block is a multi-line string literal that begins and ends with three double-quote characters ( """ ). It eliminates the need for manual escape sequences ( \n , \" ) when authoring embedded HTML, SQL, JSON, or XML snippets.
Delimiter Requirements
The opening """ delimiter may be followed only by optional white space and then a line terminator . You cannot place actual text content on the same line as the opening """ : // COMPILE ERROR: illegal text block open delimiter sequence, missing newline
// String bad = """SELECT * FROM users""";
// Correct syntax:
- String query = """
- SELECT id, name
- FROM users
- WHERE status = 'ACTIVE';
- """;
- Incidental vs. Essential Whitespace
Java separates indentation into incidental whitespace (boilerplate indentation added by an IDE or developer to keep code aligned) and essential whitespace (indentation intended to remain in the final string). During compilation, the compiler executes a three-step normalization process:
Line terminators are normalized to standard newline characters ( \n ).
Incidental whitespace is stripped : The compiler calculates the common minimum leading whitespace across all non-blank lines and the line containing the closing """ delimiter.
- Escape sequences are interpreted. String block1 = """
- Red
- Green
- Blue
- """; // Closing delimiter indented 8 spaces; all lines have 8 leading spaces stripped
- // Result: "Red\nGreen\nBlue\n"
- String block2 = """
- Red
- Green
- Blue
- """; // Closing delimiter at column 0 (0 spaces)
- // Result: " Red\n Green\n Blue\n"
Tip
Closing Delimiter Controls Indentation Baseline Placing the closing """ on its own line allows you to set the indentation margin. If you move the closing delimiter to the far left margin (column 0), all leading whitespace on every line becomes essential and is preserved!
Text Block Escape Sequences
Inside text blocks, double quotes ( " ) and double pairs ( "" ) do not require escaping . Escaping is only required for three consecutive quotes ( \"\"\" ). Java introduces two specific escape sequences for text blocks:
\ (Line continuation): Suppresses the line break, joining two lines into a single logical line.
\s (Explicit space): Translates to an ASCII space character ( \u0020 ) and preserves trailing whitespace that would otherwise be trimmed by the text block compiler algorithm. String singleLine = """
- SELECT id, name \
- FROM employees \
- WHERE active = true;
- """;
- // Result: "SELECT id, name FROM employees WHERE active = true;\n"
- String Immutability and the String Constant Pool
String objects in Java are immutable . Once created, their internal byte arrays cannot be modified. Any method that appears to modify a String (such as concat() , replace() , or toLowerCase() ) creates and returns a brand-new String object.
The String Constant Pool and intern()
The JVM maintains a specialized memory region inside the heap called the String Constant Pool to conserve memory:
String Literals : Automatically interned into the pool. Identical literals share the same object reference.
new String("abc") : Explicitly bypasses the pool, allocating a new, distinct String object on the heap.
intern() : Searches the pool for a string with equal character content. If found, returns the pooled reference; if not found, adds the string to the pool and returns its reference. String s1 = "Java";
- String s2 = "Java";
- String s3 = new String("Java");
- String s4 = s3.intern();
- System.out.println(s1 == s2); // true (both reference the same pooled literal)
- System.out.println(s1 == s3); // false (s3 is a separate heap instance)
- System.out.println(s1 == s4); // true (s4 refers to the pooled instance returned by intern())
- Compile-Time Constant Concatenation
Expressions composed purely of compile-time constants (literals or final variables) are evaluated at compile time and pooled. Expressions involving non-final variables are evaluated at runtime, producing new heap instances: String base = "Java";
final String finalBase = "Java";
- String test1 = base + " 17"; // Runtime concatenation -> new heap object
- String test2 = finalBase + " 17"; // Compile-time constant expression -> interned literal
- String literal = "Java 17";
- System.out.println(test1 == literal); // false
- System.out.println(test2 == literal); // true
- Modern String Methods (Java 11 through Java 17)
Modern Java versions introduced powerful methods on java.lang.String :
Method Introduced Purpose / Behavior
strip() Java 11 Removes leading and trailing whitespace using Unicode-aware codepoints (replaces legacy trim() , which only strips ASCII ≤ \le ≤ 32).
stripLeading() Java 11 Removes only leading whitespace.
stripTrailing() Java 11 Removes only trailing whitespace.
isBlank() Java 11 Returns true if string is empty ( length() == 0 ) or contains only white space codepoints.
lines() Java 11 Returns a Stream<String> splitting lines on \n , \r , or \r\n .
repeat(int n) Java 11 Returns string concatenated with itself n times.
formatted(Object... args) Java 15 Instance method equivalent to String.format(this, args) .
indent(int n) Java 12 Adjusts indentation of every line by n spaces (removes if negative) and normalizes line endings to \n .
transform(Function<String, R> f) Java 12 Applies the function to this string and returns the result R (enables fluent chaining). String text = " \u2000Hello Java\u2000 ";
- System.out.println(text.trim().length()); // trim() fails to remove Unicode whitespace \u2000
- System.out.println(text.strip().length()); // strip() removes full Unicode whitespace
- "abc ".repeat(3); // "abc abc abc "
- "line1\nline2".lines().count(); // 2
- String result = "hello"
- .transform(String::toUpperCase)
- .transform(s -> s + " WORLD"); // "HELLO WORLD"
- StringBuilder vs. StringBuffer
StringBuilder (introduced in Java 5) and StringBuffer (legacy Java 1.0) represent mutable sequences of characters:
StringBuilder : Not thread-safe (methods are unsynchronized). Offers maximum performance for single-threaded usage.
StringBuffer : Thread-safe (methods are synchronized). Carries locking overhead; rarely needed in modern code.
Internal Capacity Mechanics
A StringBuilder maintains an internal buffer with an initial capacity :
new StringBuilder() : Default capacity of 16 characters.
new StringBuilder(int capacity) : Explicit capacity set to specified integer.
new StringBuilder(String str) : Capacity initialized to str.length() + 16 .
When appends exceed capacity, the buffer automatically expands to (oldCapacity * 2) + 2 .
Mutation Methods and Method Chaining
All mutating methods return a reference to this ( StringBuilder ), enabling fluent method chaining: StringBuilder sb = new StringBuilder("Java");
- sb.append(" 17") // "Java 17"
- .insert(0, "Modern ") // "Modern Java 17"
- .replace(0, 6, "Fast") // "Fast Java 17"
- .delete(4, 9) // "Fast 17" (deletes indices 4 through 8 inclusive)
- .reverse(); // "71 tsaF"
Warning
The StringBuilder.equals() Trap Neither StringBuilder nor StringBuffer overrides equals() or hashCode() from java.lang.Object ! Calling sb1.equals(sb2) performs reference equality ( == ) , returning false even if both builders hold identical characters. To compare text content, convert them to strings with .toString().equals(...) or use sb1.compareTo(sb2) == 0 .
Core String Methods You Must Trace by Hand
Most String questions on the exam are about exact return values and index boundaries rather than modern additions. Indexes are zero-based, and every end index is exclusive .
- Call on String s = "animals"; Result Rule
- s.length() 7 Number of char values
- s.charAt(6) 's' charAt(7) throws StringIndexOutOfBoundsException
- s.substring(3) "mals" From index 3 to the end
- s.substring(3, 4) "m" end is exclusive
- s.substring(3, 3) "" Equal indexes return an empty string
- s.substring(4, 3) throws StringIndexOutOfBoundsException begin greater than end
- s.indexOf('a') / s.indexOf("al") 0 / 4 First match, or -1 if absent
- s.indexOf('a', 4) / s.lastIndexOf('a') 4 / 4 The second argument is the start index
- "abc".compareTo("abd") -1 Lexicographic, by char code; "apple".compareTo("app") is 2 (length difference)
- "abc".equalsIgnoreCase("ABC") true equals is case-sensitive
- "banana".replace('a', 'o') "bonono" Replaces all matches; there is also a CharSequence overload
- "a,b,,c,,".split(",") [a, b, , c] (length 4) Trailing empty strings are removed
- String.join("-", "a", "b", "c") "a-b-c" Static method
- "x" + null "xnull" Concatenation converts null to the text null
Other methods to recognize: startsWith , endsWith , contains , toUpperCase , toLowerCase , trim , isEmpty (length 0), isBlank (only whitespace), concat , and chars() (an IntStream ). Because strings are immutable, a statement such as t.concat(" 17"); that ignores the return value leaves t unchanged.
More StringBuilder methods
StringBuilder also offers deleteCharAt(int) , setCharAt(int, char) (returns void , so it cannot be chained further), setLength(int) , indexOf(String) , charAt(int) , and length() . For example, new StringBuilder("abcdef").deleteCharAt(1).insert(2, "-") produces "ac-def" , and setLength(2) on "hello" truncates it to "he" .