Text Blocks practice questions

From OCP Java SE 21 (1Z0-830) · 14 questions on this topic

Text Blocks practice questions from OCP Java SE 21 (1Z0-830). This pack has 14 questions tagged Text Blocks, drawn from its timed mock exams. 8 of them are worked through in full below — the question, every option, why each is right or wrong, and the explanation.

Worked examples for Text Blocks

  1. Question 1

    What does this print? ```java public class Main { public static void main(String[] args) { String s = """ a\s b"""; System.out.print(s.length()); } } ```

    1. A. 4Correct answer

      After the 12-space incidental indentation is stripped the lines are a\s and b; escape processing runs after stripping, so \s becomes a real space that survives. The value is a, space, newline, b — length 4.

    2. B. 2

      Treats \s like the line-continuation escape \<newline>, which would delete the newline and add nothing; but \s adds a real space instead.

    3. C. 3

      Forgets the single space contributed by the \s escape.

    4. D. 5

      Counts the backslash and s as two literal characters, but \s is a single escape producing one space.

    Explanation

    Text-block processing strips incidental white space before it processes escape sequences, so escapes always act on the already-trimmed content. The \s escape produces a single protected space that survives stripping, unlike a bare trailing backslash which merely deletes its line terminator and adds nothing. Here the value consists of the first line's character, a protected space, a newline, and the second line's character — four characters in all.

  2. Question 2

    How does the compiler determine how much leading white space to strip from each line of a text block?

    1. A. It strips indentation equal to the opening delimiter's column

      The opening delimiter's position is irrelevant to stripping; only the content lines and the closing delimiter matter.

    2. B. It always strips exactly the indentation of the first content line

      Any line can set the minimum indentation, not specifically the first one.

    3. C. It strips nothing unless stripIndent() is called explicitly on the resulting String

      Stripping happens automatically at compile time; String.stripIndent() merely exposes the same algorithm for runtime strings.

    4. D. It strips the minimum indentation found among the non-blank content lines and the closing delimiter's line (when the delimiter is on its own line)Correct answer

      The re-indentation algorithm computes the common prefix as the minimum indentation over the non-blank content lines, and a closing delimiter on its own line participates in that minimum — which is why sliding it further left preserves extra indentation on every line.

    Explanation

    The compiler determines incidental white space by taking the minimum indentation across all non-blank content lines, and it includes the closing delimiter's line in that computation when the delimiter stands alone. This stripping happens automatically at compile time, independent of the opening delimiter's column and not tied to any single line. Sliding the closing delimiter leftward lowers the minimum and thus preserves extra indentation throughout the value.

  3. Question 3

    Which two statements about text blocks are correct? (Choose two.)

    1. A. A text block produces an ordinary java.lang.String — no new runtime type is introducedCorrect answer

      A text block is just an alternative literal syntax whose type is String, so every String method, concatenation, and switch usage works unchanged and no new runtime type is introduced.

    2. B. Text blocks substitute variables written as ${name} into the value

      Java text blocks have no interpolation; ${name} is not substituted. To insert values you combine the block with formatted() or String.format.

    3. C. A double quote can appear inside a text block without any escapingCorrect answer

      Because the delimiter is three quotes, a lone double quote (or even two) inside the content is plain content; only a run of three consecutive quotes needs one of them escaped.

    4. D. Trailing spaces at the end of each line are preserved in the value by default

      The compiler strips trailing white space from every line of a text block; to keep a deliberate trailing space you must end the line with the \s escape.

    Explanation

    A text block is only new syntax for producing an ordinary String, so it introduces no runtime type and supports every String operation unchanged. Because its delimiter is three double-quotes, single or double quotes inside the content need no escaping — only three consecutive quotes do. Java text blocks perform no variable interpolation, and trailing white space on each line is silently stripped unless explicitly protected.

  4. Question 4

    What does this program print? ```java public class Main { public static void main(String[] args) { String a = """ red green"""; String b = "red\ngreen"; System.out.print((a == b) + "," + a.equals(b)); } } ```

    1. A. false,false

      Assumes a text block always ends in a line terminator, so identity would fail. But the closing delimiter sits on the `green` line, so no line break is added and the content is exactly "red\ngreen" — the same interned literal that `b` names — making both comparisons true.

    2. B. The code does not compile: the closing delimiter must be on a line of its own

      Only the OPENING delimiter requires a line terminator after it; the closing delimiter may end the last content line, which is precisely how you get a string with no trailing newline. The code therefore compiles.

    3. C. true,trueCorrect answer

      A text block IS a string literal (JLS 21 §3.10.6) and a constant expression, so the compiler interns it in the string pool just like a traditional literal; incidental whitespace removal and escape translation happen at compile time, so `a` is the same pooled "red\ngreen" that `b` refers to — identity and equality are both true.

    4. D. false,true

      Encodes the common misconception that a text block is assembled at run time (a StringBuilder or fresh String), so the contents match but the references differ. Nothing about a text block is deferred to run time; it is a compile-time literal, so `==` is also true.

    Explanation

    Trace: a text block IS a string literal (JLS 21 §3.10.6), so it is a constant expression and the compiler interns it in the string pool exactly like a traditional literal. Incidental whitespace removal, escape translation and line terminator normalisation all happen at COMPILE time, so `a` is the constant "red\ngreen" — the same pooled object that `b` refers to. Both content lines are indented 12 and the closing delimiter sits on the last content line, so nothing is left over and no trailing newline is added. Identity and equality are therefore both true. Why the others are wrong: `false,true` encodes the commonest misconception — that a text block is assembled at run time (a StringBuilder or a fresh String), so the contents match but the references differ. Nothing about a text block is deferred to run time; it is a literal in the class file's constant pool. `false,false` assumes a text block always ends in a line terminator. The trailing newline comes from the LINE BREAK before a closing delimiter that sits on its own line — here the closing """ is on the `green` line, so there is no such break and the content ends at `green`. `The code does not compile: the closing delimiter must be...` encodes the belief that the closing delimiter is required to stand alone. Only the OPENING delimiter has a mandatory line terminator after it; the closing one may end the last content line, and doing so is precisely how you get a string with no trailing newline. Exam tip: text blocks are pure compile-time sugar — `==` against an equal literal is true, and a text block is legal wherever a constant expression is required (a `case` label, an annotation element, a `static final` initialiser). The reverse trap: give the closing delimiter its own line and the string gains a trailing `\n`, which silently breaks `==` against a literal that lacks one.

  5. Question 5

    What does this print? ```java public class Main { public static void main(String[] args) { String s = """ "quoted" """; System.out.print(s.length()); } } ```

    1. A. 8

      Counts only the visible characters and misses the trailing newline produced by the own-line closing delimiter.

    2. B. 9Correct answer

      The quote characters around the word are ordinary content, so the content line is 8 characters; the closing delimiter stands on its own line, adding a trailing newline for a total of 9.

    3. C. 10

      Counts a character that is not there; the 12-space indentation is common to both lines and fully stripped.

    4. D. Compilation fails: quotes inside a text block must be escaped

      It compiles: double quotes need no escaping inside a text block unless three appear consecutively.

    Explanation

    Count a text block's length in two steps: the visible characters remaining after incidental white space is stripped, plus one trailing newline only when the closing delimiter sits on its own line. Double quotes inside a text block are ordinary content and need no escaping unless three appear consecutively. Here the quoted word contributes its visible characters and the own-line closing delimiter adds one trailing newline.

  6. Question 6

    What does the following program print? ```java public class Main { public static void main(String[] args) { String s = """ one \s """; System.out.print(s.length()); } } ```

    1. A. 3

      Discounts both the trailing spaces and the newline contributed by the closing `"""` on its own line, leaving only the three characters of "one". The closing delimiter placed on its own indented line always appends a newline to the content, and the two explicit spaces before `\s` are not leading (incidental) whitespace so they survive step 2 unchanged.

    2. B. 7Correct answer

      JEP 378 processes text block content in three steps: (1) normalise line terminators, (2) strip incidental leading whitespace and trailing whitespace from each content line, (3) interpret escape sequences. In step 2 the content line is "one \s" — the two-character sequence \s is not whitespace, so nothing is trimmed from the right. In step 3, \s → U+0020, producing "one " (three trailing spaces). Because the closing `"""` sits on its own indented line, a newline is appended, giving s == "one \n" — seven characters.

    3. C. 4

      The result of reversing the processing order: if escape sequences were interpreted before trailing whitespace was stripped, `\s` would first become a space and that space would then be stripped, leaving "one\n" — four characters. JEP 378 specifies the opposite order — trailing whitespace is stripped in step 2 (re-indentation) and escapes are interpreted only in step 3 — so the space produced by `\s` never reaches the stripper.

    4. D. 6

      Treats `\s` as a no-op that is silently dropped, leaving "one \n" (two spaces plus newline = 6 characters). The `\s` escape is not discarded: it is a recognised text-block escape sequence that expands to exactly one space (U+0020), appending a third trailing space after the two already present.

    Explanation

    Text block content is processed in three ordered steps (JEP 378): normalise line terminators, strip incidental leading whitespace and trailing whitespace from each content line, then interpret escape sequences. Because trailing-whitespace stripping runs in step 2 — before escape interpretation in step 3 — the stripper sees `\s` as two non-whitespace characters (`\` and `s`) and leaves the line untouched; only in step 3 does `\s` expand to a single space (U+0020), adding a third trailing space to the two already present. The closing `"""` on its own indented line also contributes a final newline, making the string seven characters in total. Reversing steps 2 and 3 would cause the produced space to be stripped (length 4); treating `\s` as a no-op would drop that one space (length 6); discounting both the `\s`-produced space and the closing-delimiter newline would give just the three letters of "one" (length 3).

  7. Question 7

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { String s = """ Hello \ World """; System.out.print(s); } } ```

    1. A. Hello \ World

      This treats `\` at the end of a content line as a literal backslash character retained in the string value. JEP 378 defines `\<line-terminator>` as an escape sequence; during step 3 the compiler removes both the backslash and the line terminator it precedes, so neither character appears in the resulting string.

    2. B. HelloWorld

      The `\<line-terminator>` escape removes exactly the backslash and the newline that immediately follows it — not the space that precedes the backslash on the source line. The first content line reads `Hello \`; the space is part of `Hello ` and sits before (not within) the escape sequence, so it survives into the value and the two words join as `Hello World`, not `HelloWorld`.

    3. C. Compilation fails

      JEP 378 explicitly introduces `\<line-terminator>` as a legal escape sequence for text blocks (and tolerates it in traditional string literals as well). The compiler accepts it during step 3 of text-block processing; the program compiles and runs without error.

    4. D. Hello WorldCorrect answer

      The `\` at the end of the first content line is immediately followed by the line terminator, forming the `\<line-terminator>` escape introduced in JEP 378. Text-block processing applies escape sequences in step 3, after step 2 has already stripped the 16-space common indent. Step 3 removes both the backslash and the following LF entirely. The space that precedes the backslash on that source line is not part of the escape and is retained, so `Hello ` and `World` are joined as `Hello World`. The closing `"""` on its own indented line contributes a trailing newline, giving `s` the value `"Hello World\n"`; `System.out.print` writes exactly that.

    Explanation

    Text-block content is processed in three ordered steps per JEP 378: line terminators are normalised to LF, incidental whitespace is stripped using the minimum indentation across all non-blank content lines and the closing delimiter's column, and then escape sequences are interpreted — in that order. After the 16-space common prefix is removed, the two content lines become `Hello \` and `World`, and a trailing newline is contributed by the closing `"""` sitting on its own line; escape processing then erases the `\<line-terminator>` pair entirely — the backslash plus the LF that follows it — joining them as `Hello World` because the space that precedes the backslash is outside the escape and is unaffected. The distractor showing a literal backslash in the output treats a defined escape sequence as a printable character; the distractor that drops the space incorrectly extends the escape's reach to consume the preceding space; and the compilation-failure distractor does not know that `\<line-terminator>` was introduced as a legal escape in JEP 378.

  8. Question 8

    Note the backslash at the end of the text block's only content line. What does this program print? ```java public class Main { public static void main(String[] args) { String s = """ {"name": "%s"}\ """.formatted("ok"); System.out.print(s + "|" + s.length()); } } ```

    1. A. {"name": "%s"}|14

      Assumes a text block is a raw string in which %s is inert. A text block is an ordinary String, so formatted substitutes ok for %s exactly as for any String; the 14 is a coincidence, since {"name": "%s"} is also 14 characters.

    2. B. {"name": "ok"}|14Correct answer

      The trailing backslash is the line-continuation escape, suppressing the newline before the closing delimiter, so the content is one line with no trailing newline; formatted then substitutes ok, giving 14 characters.

    3. C. The code does not compile: the " characters inside a text block must be escaped

      Inverts the headline benefit of text blocks. A lone " needs no escaping inside one; only a run of three consecutive quotes needs a backslash, so the code compiles.

    4. D. {"name": "ok"} |15

      Ignores the trailing backslash: this is what the identical block without it prints, where the own-line closing delimiter leaves a trailing newline and length rises to 15. Suppressing exactly that newline is what the backslash does.

    Explanation

    Trace: a `\` as the last character of a line inside a text block is the line-continuation escape — it suppresses the line terminator that would otherwise be inserted there. The break being suppressed is the one before the closing delimiter, so the block's content is `{"name": "%s"}` with NO trailing newline. Escapes are translated after incidental whitespace is removed, so the 12-space common prefix (content line and closing delimiter alike) comes off first and nothing survives it. `formatted` then substitutes `ok` for `%s`, giving `{"name": "ok"}` — 14 characters, all on one line. Why the others are wrong: The option printing the JSON, then a line break, then `|15` ignores the trailing `\`: it is what you get from the identical block WITHOUT that backslash, where the own-line closing delimiter leaves a trailing `\n` and the length rises to 15. Suppressing exactly that newline is the reason `\` exists. `{"name": "%s"}|14` assumes a text block is a raw string in which `%s` is inert. A text block is an ordinary `java.lang.String` — no new type, no raw semantics — so `formatted` treats `%s` as a conversion exactly as it would for any other String. (The 14 is a coincidence: `{"name": "%s"}` is also 14 characters.) `The code does not compile: the " characters...` inverts the headline benefit of text blocks. A lone `"` needs no escaping inside one; only a run of three consecutive quotes needs a backslash to keep it from closing the block. Exam tip: `\` at end of line joins lines (removes a newline); `\s` at end of line preserves the space before it against the trailing-whitespace strip (and is itself a space). Both are applied AFTER indent stripping, so neither can protect leading indentation.

Practise all 14 Text Blocks questions

OCP Java SE 21 has the full set, inside timed mock exams that mirror real exam conditions — every question with a worked explanation.

Open OCP Java SE 21

Other topics in this pack