Text Blocks practice questions

From OCP Java SE 25 (1Z0-831) · 14 questions on this topic

Text Blocks practice questions from OCP Java SE 25 (1Z0-831). 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 = """ foo\ bar baz"""; System.out.println(s.replace("\n", "|")); } } ```

    1. A. foo|bar|baz

      Treats the trailing backslash as a normal character and keeps the newline it was meant to remove.

    2. B. foobarbaz

      Removes BOTH newlines; only the one after the backslash-continued line is suppressed.

    3. C. foo\bar|baz

      Keeps the backslash in the value; the continuation escape is consumed and never appears in the string.

    4. D. foobar|bazCorrect answer

      The trailing backslash after foo is the line-continuation escape: it deletes that line terminator, joining foo and bar into foobar; the newline after bar is ordinary content and baz shares its line with the closing delimiter, so replacing \n with | prints foobar|baz.

    Explanation

    A backslash at the end of a line inside a text block is the line-continuation escape: it suppresses exactly one line terminator and leaves no character behind, so foo and bar merge into foobar. The remaining newline after bar is ordinary content, and baz shares its line with the closing delimiter, so no further newline follows. Replacing the single remaining newline with a pipe yields foobar|baz.

  2. Question 2

    What does this program print? ```java public class Main { public static void main(String[] args) { String s = """ red green blue"""; System.out.print(s.lines().count() + ":" + s.endsWith("\n")); } } ```

    1. A. 3:falseCorrect answer

      The closing delimiter sits on the same line as `blue`, so the block has exactly three content lines and no trailing newline: lines() yields 3 and endsWith("\n") is false.

    2. B. 4:true

      Assumes a trailing newline and then counts the empty remainder as a fourth line; only a closing delimiter on its own line adds a newline, and lines() never reports a trailing empty line anyway.

    3. C. 3:true

      Gets the line count right but believes every text block ends with a newline; only a closing delimiter on its own line adds one, and here it follows `blue` on the same line.

    4. D. 4:false

      Counts lines as terminators-plus-one and also imagines an extra empty line at the end, which cannot coexist with there being no trailing newline.

    Explanation

    Trace: the closing delimiter sits on the same line as `blue`, not on a line of its own. That is what decides the trailing newline: the block has exactly three content lines and no line terminator after the last of them, so the value is red, newline, green, newline, blue. `String.lines()` splits on line terminators and yields three lines, and `endsWith("\n")` is false. Why the others are wrong: `3:true` gets the line count right but believes every text block ends with a newline. Only a closing delimiter on its OWN line adds one. `4:true` makes that same mistake and then counts the empty remainder after the imagined trailing newline as a fourth line. `String.lines()` never reports a trailing empty line anyway — `"a\nb\n".lines().count()` is 2, not 3. `4:false` counts lines as terminators-plus-one but also imagines an extra empty line at the end, which cannot coexist with there being no trailing newline. Exam tip: the closing `"""` is a switch. On its own line it contributes a trailing newline (and its indentation joins the incidental-whitespace calculation, so putting it further left adds spaces to every line). On the last content line it contributes neither.

  3. Question 3

    What is the result of compiling and running this program? ```java public class Main { public static void main(String[] args) { String s = """hello world"""; System.out.println(s); } } ```

    1. A. helloworld

      Assumes the code compiles and the line break is a continuation; it never reaches compilation.

    2. B. Compilation fails: the opening """ must be followed by a line terminator, not contentCorrect answer

      The opening delimiter is three double-quotes followed by optional white space and then a MANDATORY line terminator, so hello immediately after the opening """ makes javac report an illegal open delimiter and the program never runs.

    3. C. hello world

      Assumes hello becomes the first content line; content on the opening line is illegal, so no value is produced.

    4. D. hello world

      Assumes both that it compiles and that indentation is not stripped; neither holds.

    Explanation

    The opening """ of a text block must be followed only by optional white space and then a line terminator, so the first content character has to start on the next line. Here hello sits immediately after the opening delimiter, which javac rejects as an illegal open delimiter sequence, so the program fails to compile. Only the closing delimiter may share a line with content.

  4. Question 4

    The second content line of the text block ends with a `\n` escape. What does this program print? (Newlines in the result are shown as `|`.) ```java public class Main { public static void main(String[] args) { String s = """ alpha beta\n gamma"""; System.out.print(s.replace("\n", "|")); } } ```

    1. A. alpha|beta||gammaCorrect answer

      Correct: escapes are interpreted last, after the line's own terminator is already present, so the typed \n on the beta line adds an extra newline, producing an empty line between beta and gamma (alpha|beta||gamma).

    2. B. alpha|beta|gamma

      Assumes the typed \n is absorbed into the line's own terminator as if it merely restated it; nothing merges the two, so you get both newlines.

    3. C. alpha|betagamma

      Confuses \n with a lone trailing backslash: a trailing backslash suppresses the line's newline and joins the lines, whereas \n does the opposite and adds one.

    4. D. alpha|beta\n|gamma

      Treats the text block as a raw string in which escapes are never processed; Java has no raw string, so the escape-interpretation step always runs and the \n becomes a real newline.

    Explanation

    Trace: a text block is processed in three fixed steps. (1) line terminators are normalised to \n; (2) incidental whitespace is removed; (3) escape sequences are interpreted. Step 2 strips the 16-space indent, leaving three content lines: `alpha`, `beta\n` (four characters: b, e, t, a, then a backslash and an n) and `gamma`, joined by the block's own line terminators. Only in step 3 does the two-character `\n` you typed become a line terminator — and it is an EXTRA one, on top of the newline the source line already carried. The value is alpha, newline, beta, newline, newline, gamma: an empty line between beta and gamma. Why the others are wrong: `alpha|beta|gamma` assumes the typed `\n` is absorbed into the line's own terminator, as if it merely restated it. Nothing merges the two — you get both. `alpha|beta\n|gamma` treats a text block as a raw string in which escapes are never processed (Python's r-string, C#'s @-string). Java has no raw string: step 3 always runs, and `\t`, `\"`, `\\` and `\n` all mean what they mean in a traditional literal. `alpha|betagamma` confuses `\n` with the other line-level escape, a lone trailing backslash. A trailing `\` SUPPRESSES the line's newline and joins the two lines; `\n` does the opposite and adds one. Exam tip: escapes are interpreted LAST, after the whitespace has already gone. That single ordering rule explains both traps on this topic — why a typed `\n` is additive, and why `\s` rescues a trailing space (when step 2 runs, `\s` is still a backslash and an s, which are not whitespace, so nothing is stripped).

  5. Question 5

    The text block below has a completely blank line between its two content lines, and the two content lines are indented differently. Newlines are then shown as `|` and spaces as `.`. What is printed? ```java public class Main { public static void main(String[] args) { String s = """ alpha beta"""; System.out.print(s.replace("\n", "|").replace(" ", ".")); } } ```

    1. A. ..alpha|beta

      Assumes the blank line is dropped; a blank line survives as an empty line, producing two consecutive newlines.

    2. B. ..alpha||betaCorrect answer

      Incidental indentation is the minimum over the non-blank lines, taken from the second line, so the first content line keeps two leading spaces and the second none; the blank line survives, giving the two-space content, a newline, an empty line, another newline, then the second content.

    3. C. alpha||beta

      Assumes all leading white space is stripped; only the common minimum indentation is removed, leaving two spaces before the first content line.

    4. D. ................alpha||..............beta

      Assumes the blank line participates in the minimum-indentation calculation; blank lines are excluded, so stripping is not cancelled.

    Explanation

    A text block's incidental white space is the smallest indentation among its non-blank content lines (and the closing delimiter's own line), and lines that are entirely white space are excluded from that computation. The common indentation is stripped from every line, so differently indented lines keep different residual leading spaces, and a blank line remains as an empty line. With the closing delimiter on the last content line there is no trailing newline.

  6. Question 6

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

    1. A. true trueCorrect answer

      Correct: incidental whitespace is stripped at compile time, making the text block a constant String literal that is interned into the shared pool alongside "hi", so == and equals are both true.

    2. B. false true

      Assumes a text block is assembled at run time (a new String) so it could never be == to a literal; that is right for a computed String but wrong for one the compiler folds to a constant.

    3. C. true false

      Inverts the two operators, treating == as a character comparison and equals as identity; both readings are backwards, and two references can never be identical yet unequal.

    4. D. false false

      Assumes stripping the indentation leaves something other than "hi" (a leading space, say) so even equals fails; every content line loses the same 16 characters, so the value is exactly "hi".

    Explanation

    Trace: incidental whitespace is removed at COMPILE time, not at run time. javac strips the 16 spaces of indentation while it is still lexing, so it knows the value of the text block — `hi` — before any code runs. A text block is a string literal (JLS 25 3.10.6), which makes `a` a constant expression, and the value of a constant String expression is interned into the shared pool (JLS 25 3.10.5). The literal `"hi"` assigned to `b` is interned into that same pool, so both references point at one object: `a == b` is true, and `a.equals(b)` is true as well. Why the others are wrong: `false true` encodes the most common belief here — that a text block is assembled at run time (a `new String`, or a StringBuilder joining the lines), so it could never be `==` to a literal. That is exactly right for a String you compute, and wrong for one the compiler folds. `false false` stacks a second error on the first: that stripping the indentation leaves something other than `hi` (a leading space, say), so even `equals` would fail. It does not — every content line loses the same 16 characters. `true false` is the classic inversion of the two operators: that `==` compares the characters and `equals` compares object identity. Both readings are backwards, and no pair of references can ever be identical yet unequal. Exam tip: because the whitespace is gone by compile time, a text block is a constant expression — it can be interned, used as a `case` label, and used as an annotation element value. Reverse trap: concatenate a non-constant into it (`a + name`) and the result is built at run time, so `==` against a literal turns false.

  7. Question 7

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

    1. A. Line terminators in the source — including a CRLF written by a Windows editor — are normalized to \n in the resulting StringCorrect answer

      The first step of text-block processing translates every source line terminator, including a CRLF written by a Windows editor, to a single \n, so the value is portable across platforms.

    2. B. A lone double quote inside the content must be escaped as \"

      Because the delimiter is three quotes, a single " (or even two in a row) is plain content and needs no escaping; only a run of three or more consecutive quotes requires escaping one.

    3. C. Trailing white space on each line is stripped from the value unless preserved with the \s escapeCorrect answer

      The compiler removes trailing white space from every line; to keep a deliberate trailing space you end the line with the \s escape, which expands to one space after stripping.

    4. D. Content may begin on the same line as the opening """ delimiter

      The opening delimiter must be followed by optional white space and then a line terminator; putting content on the opening line is a compile-time error.

    Explanation

    Two silent normalizations define text blocks. Every source line terminator, whatever the editor wrote, is collapsed to a single \n so the value is platform-independent, and trailing white space on each line is stripped unless deliberately preserved with the \s escape. Both changes are invisible in the source, so reason about the resulting value rather than the raw characters on screen.

  8. Question 8

    The first content line of the text block ends with the Unicode escape `\u0020`, which is the code point of the space character. What is the length of s? ```java public class Main { public static void main(String[] args) { String s = """ ab\u0020 c"""; System.out.print(s.length()); } } ```

    1. A. Compilation fails: a Unicode escape cannot appear inside a text block

      Half-remembers a real rule about a different escape; a Unicode escape for a line terminator causes trouble only in a traditional string literal, while \u0020 is legal inside a text block and simply becomes a space.

    2. B. 4Correct answer

      \u0020 is translated to a real space in the first compilation step, before the text-block rules run, so the first content line ends in a trailing space that incidental-whitespace removal deletes; the value is a, b, newline, c — length 4.

    3. C. 5

      Assumes \u0020 protects a trailing space the way \s does; it cannot — \u0020 has already become a space three steps earlier, whereas \s is processed last and so survives the whitespace stripping.

    4. D. 10

      Treats the text block as a raw string in which nothing is decoded, counting the six source characters of the escape plus ab, the newline, and c.

    Explanation

    Trace: a Unicode escape is not a string escape. It is translated in the very FIRST step of compilation (JLS 25 3.3), before javac has even worked out where the text block's delimiters are — so the compiler never sees the six characters you typed, it sees a real space. By the time the text-block rules run, the first content line genuinely ends in a trailing space, and incidental-whitespace removal deletes trailing white space from every line. javac says so out loud: compile this stem with `-Xlint:all` and it reports `warning: [text-blocks] trailing white space will be removed`. The value is a, b, newline, c — length 4. Why the others are wrong: `5` is the whole point of the question: it assumes a Unicode escape protects a trailing space the way `\s` does. It cannot. `\s` survives because it is still a backslash and an s when the whitespace is stripped, and only turns into a space in the final escape-processing step. A Unicode escape has already become a space three steps earlier. `10` treats a text block as a raw string in which nothing is decoded, counting the six source characters of the escape plus ab, the newline and c. `Compilation fails: a Unicode escape cannot appear inside a text block` half-remembers a real rule about a different escape. A Unicode escape for a LINE TERMINATOR is what causes trouble, and only in a traditional string literal, where it ends the line early. Inside a text block it simply becomes an extra line break, and `\u0020` is legal anywhere. Exam tip: to keep a trailing space, `\s` is the only tool — it is defined to be processed last, precisely so that it can outlive the whitespace stripping. If you see `\u0020` at the end of a line in an exam stem, read it as a plain space that is about to be deleted.

Practise all 14 Text Blocks questions

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

Open OCP Java SE 25

Other topics in this pack