[{"data":1,"prerenderedAt":113},["ShallowReactive",2],{"qa-\u002Fjava\u002Fmodern-java\u002Ftext-blocks":3},{"page":4,"siblings":81,"blog":110},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":20,"path":21,"questions":22,"questionsCount":72,"related":73,"seo":74,"seoDescription":75,"stem":76,"subtopic":6,"topic":77,"topicSlug":78,"updated":79,"__hash__":80},"qa\u002Fjava\u002Fmodern-java\u002Ftext-blocks.md","Text Blocks",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"easy","md","Java","java",{},true,4,"\u002Fjava\u002Fmodern-java\u002Ftext-blocks",[23,27,31,36,40,44,48,52,56,60,64,68],{"id":24,"difficulty":14,"q":25,"a":26},"what-are-text-blocks","What are text blocks in Java and what problem do they solve?","**Text blocks** (Java 15, JEP 378) are multi-line string literals enclosed\nin triple double-quotes (`\"\"\"`). They eliminate the need for explicit `\\n`,\n`\\\"`, and string concatenation when embedding multi-line content like JSON,\nSQL, HTML, or XML.\n\n```java\n\u002F\u002F Old way — hard to read, easy to make mistakes:\nString json = \"{\\n\" +\n              \"  \\\"name\\\": \\\"Alice\\\",\\n\" +\n              \"  \\\"age\\\": 30\\n\" +\n              \"}\";\n\n\u002F\u002F Text block — reads like the actual content:\nString json = \"\"\"\n        {\n          \"name\": \"Alice\",\n          \"age\": 30\n        }\n        \"\"\";\n```\n\n**Rule of thumb:** use text blocks for any multi-line string — SQL,\nJSON, HTML, XML, or test fixtures; never concatenate `\\n` manually again.\n",{"id":28,"difficulty":14,"q":29,"a":30},"opening-closing-delimiter","What are the rules for the opening and closing \"\"\" delimiters?","- The **opening** `\"\"\"` must be followed by a newline — content cannot\n  start on the same line as the opening delimiter.\n- The **closing** `\"\"\"` can be on its own line or at the end of the last\n  content line.\n- The position of the closing `\"\"\"` determines the amount of\n  **incidental whitespace** stripped.\n\n```java\n\u002F\u002F Closing \"\"\" on its own line — trailing newline included:\nString s1 = \"\"\"\n        hello\n        world\n        \"\"\";\n\u002F\u002F s1 = \"hello\\nworld\\n\"\n\n\u002F\u002F Closing \"\"\" at end of last line — no trailing newline:\nString s2 = \"\"\"\n        hello\n        world\"\"\";\n\u002F\u002F s2 = \"hello\\nworld\"\n```\n\n**Rule of thumb:** put the closing `\"\"\"` on its own line for content that\nshould end with a newline (files, SQL); inline it to suppress the trailing\nnewline.\n",{"id":32,"difficulty":33,"q":34,"a":35},"incidental-whitespace","medium","What is incidental whitespace and how does the compiler strip it?","**Incidental whitespace** is the leading spaces added to align a text\nblock with the surrounding code indentation. The compiler removes it\nautomatically, keeping only the relative indentation within the block.\n\nThe algorithm finds the **common leading whitespace prefix** across all\nnon-blank content lines and the closing delimiter line, then strips that\nprefix from every line:\n\n```java\nString sql = \"\"\"\n        SELECT *\n        FROM users\n        WHERE active = true\n        \"\"\";\n\u002F\u002F Each content line has 12 spaces; closing \"\"\" has 12 spaces.\n\u002F\u002F Compiler strips 12 spaces → result:\n\u002F\u002F \"SELECT *\\nFROM users\\nWHERE active = true\\n\"\n```\n\nYou can **increase** relative indentation by indenting content lines more\nthan the closing delimiter:\n\n```java\nString indented = \"\"\"\n        outer\n            inner\n        \"\"\";\n\u002F\u002F \"outer\\n    inner\\n\"  — inner has 4 extra spaces relative to outer\n```\n\n**Rule of thumb:** align the closing `\"\"\"` with the minimum indentation\nyou want in the output; the compiler strips everything up to that column.\n",{"id":37,"difficulty":33,"q":38,"a":39},"line-endings","How does Java handle line endings in text blocks?","The Java compiler **normalises** all line endings in text blocks to `\\n`\n(LF) regardless of the OS line ending in the source file. This makes\ntext blocks portable across Windows (CRLF) and Unix (LF) systems without\nany special handling.\n\n```java\nString s = \"\"\"\n        line1\n        line2\n        \"\"\";\n\u002F\u002F Always \"line1\\nline2\\n\" — never \"line1\\r\\nline2\\r\\n\"\n```\n\nIf you explicitly need `\\r\\n` (e.g., for HTTP headers or email), use\nthe `\\r` escape:\n\n```java\nString crlf = \"\"\"\n        Content-Type: text\u002Fhtml\\r\n        Content-Length: 42\\r\n        \\r\n        \"\"\";\n```\n\n**Rule of thumb:** text blocks use `\\n` everywhere — don't worry about\nCRLF portability; handle it explicitly only when the protocol requires it.\n",{"id":41,"difficulty":33,"q":42,"a":43},"text-block-escapes","What new escape sequences were introduced for text blocks?","Java 15 added two new escape sequences specifically for text blocks:\n\n**`\\\u003Cline terminator>`** (line continuation) — suppresses the newline at\nthe end of a line, joining it with the next line. Useful for long logical\nlines you want to wrap visually:\n\n```java\nString sentence = \"\"\"\n        The quick brown fox \\\n        jumps over the lazy dog.\n        \"\"\";\n\u002F\u002F \"The quick brown fox jumps over the lazy dog.\\n\"\n```\n\n**`\\s`** (explicit space) — a single space that prevents trailing-space\nstripping. The compiler strips trailing whitespace from each line; `\\s`\nmarks a space that must be preserved:\n\n```java\nString padded = \"\"\"\n        red  \\s\n        green\\s\n        blue \\s\n        \"\"\";\n\u002F\u002F Each line ends with exactly one trailing space\n```\n\n**Rule of thumb:** use `\\` to join wrapped lines; use `\\s` to preserve\ntrailing spaces that would otherwise be stripped.\n",{"id":45,"difficulty":14,"q":46,"a":47},"formatted-method","How do you interpolate values into a text block?","Text blocks do not support template syntax natively. Use\n`String.formatted()` (or `String.format()`) to substitute values:\n\n```java\nString name = \"Alice\";\nint age = 30;\n\nString json = \"\"\"\n        {\n          \"name\": \"%s\",\n          \"age\": %d\n        }\n        \"\"\".formatted(name, age);\n\u002F\u002F {\"name\":\"Alice\",\"age\":30}\n```\n\n`String.formatted()` (added in Java 15) is the instance-method equivalent\nof `String.format()`, making the chain read naturally after a text block.\n\n**Rule of thumb:** use `.formatted()` for simple substitution; for\ncomplex templates with loops or conditionals, prefer a template engine\n(Mustache, Thymeleaf) rather than string manipulation.\n",{"id":49,"difficulty":14,"q":50,"a":51},"text-block-vs-string","Is a text block a different type from String?","No. A text block is just a **compile-time literal** that produces a\nregular `java.lang.String`. At runtime there is no difference between a\ntext block and a regular `String` literal — they are the same type.\n\n```java\nString a = \"hello\\nworld\\n\";\nString b = \"\"\"\n        hello\n        world\n        \"\"\";\nSystem.out.println(a.equals(b)); \u002F\u002F true — same content, same type\nSystem.out.println(a == b);      \u002F\u002F likely true — interned constants\n```\n\nBecause text blocks are string literals they are **interned** (pooled)\njust like regular literals.\n\n**Rule of thumb:** treat text blocks as a nicer syntax for string\nliterals — same type, same pool, same API.\n",{"id":53,"difficulty":14,"q":54,"a":55},"text-block-sql","Show a realistic example of a text block used for SQL.","Text blocks make multi-line SQL readable and maintainable, preserving\nthe visual structure of the query:\n\n```java\nString query = \"\"\"\n        SELECT u.id, u.name, o.total\n        FROM users u\n        JOIN orders o ON o.user_id = u.id\n        WHERE u.active = true\n          AND o.created_at > :since\n        ORDER BY o.total DESC\n        LIMIT :limit\n        \"\"\";\n\n\u002F\u002F Use with JDBC or JPA:\nQuery q = em.createNativeQuery(query, UserOrderDto.class)\n            .setParameter(\"since\", startDate)\n            .setParameter(\"limit\", 100);\n```\n\nCompare this to the pre-Java-15 alternative of quote-and-concatenate —\nthe text block is directly readable and diffable.\n\n**Rule of thumb:** text blocks are especially valuable for SQL, where\nkeyword alignment (SELECT\u002FFROM\u002FWHERE\u002FORDER BY) aids readability at a glance.\n",{"id":57,"difficulty":33,"q":58,"a":59},"text-block-trailing-whitespace","What happens to trailing whitespace on lines inside a text block?","The compiler **strips trailing whitespace** from every line of a text\nblock. This means spaces or tabs at the end of a content line are silently\nremoved. This is usually desirable (cleaner output), but can surprise you\nif you intend to produce trailing spaces (e.g., in fixed-width formatted\noutput).\n\n```java\nString padded = \"\"\"\n        item     \n        total    \n        \"\"\";\n\u002F\u002F Trailing spaces on each line are GONE:\n\u002F\u002F \"item\\ntotal\\n\"\n```\n\nUse `\\s` to anchor a trailing space that must be preserved:\n\n```java\nString padded = \"\"\"\n        item  \\s\n        total \\s\n        \"\"\";\n\u002F\u002F \"item  \\ntotal \\n\"  — one preserved trailing space per line\n```\n\n**Rule of thumb:** never rely on trailing spaces in text blocks; use\n`\\s` explicitly whenever a trailing space is meaningful.\n",{"id":61,"difficulty":14,"q":62,"a":63},"text-block-html","Show a realistic example of a text block used for HTML.","Text blocks eliminate the visual noise of escaping quotes in HTML\nattributes:\n\n```java\nString html = \"\"\"\n        \u003C!DOCTYPE html>\n        \u003Chtml lang=\"en\">\n        \u003Chead>\n          \u003Cmeta charset=\"UTF-8\">\n          \u003Ctitle>%s\u003C\u002Ftitle>\n        \u003C\u002Fhead>\n        \u003Cbody>\n          \u003Ch1>%s\u003C\u002Fh1>\n        \u003C\u002Fbody>\n        \u003C\u002Fhtml>\n        \"\"\".formatted(title, heading);\n```\n\nPreviously every `\"` inside the HTML needed escaping as `\\\"`, making\nattributes like `lang=\"en\"` look like `lang=\\\"en\\\"` — difficult to read\nand error-prone to edit.\n\n**Rule of thumb:** if your string contains `\"` characters (HTML, JSON,\nSQL string literals), a text block eliminates escape clutter entirely.\n",{"id":65,"difficulty":33,"q":66,"a":67},"text-block-indentation-control","How do you control indentation in the output of a text block programmatically?","Java 15 also added `String.indent(int n)` which adjusts the indentation\nof each line in a string by `n` spaces (positive = add, negative = remove):\n\n```java\nString block = \"\"\"\n        line1\n        line2\n        \"\"\";\n\n\u002F\u002F Add 4 spaces of indentation to every line:\nSystem.out.print(block.indent(4));\n\u002F\u002F     line1\n\u002F\u002F     line2\n\u002F\u002F                ← trailing newline preserved\n\n\u002F\u002F Remove spaces (clamped at 0 per line):\nSystem.out.print(block.indent(-2));\n```\n\n`String.stripIndent()` (also Java 15) performs the same incidental\nwhitespace removal the compiler does, useful for text blocks received\nfrom external sources at runtime.\n\n**Rule of thumb:** use `indent()` for post-processing indentation;\nuse `stripIndent()` to clean up dynamically loaded multi-line strings\nthe same way the compiler cleans text block literals.\n",{"id":69,"difficulty":14,"q":70,"a":71},"text-block-java-version","In which Java version did text blocks become a standard feature?","Text blocks were introduced as a **preview** feature in Java 13 (JEP 355)\nand Java 14 (JEP 368), then finalized as a standard feature in\n**Java 15** (JEP 378). No `--enable-preview` flag is needed in Java 15+.\n\n```java\n\u002F\u002F Java 13\u002F14 — required --enable-preview at compile and runtime\n\u002F\u002F Java 15+   — standard feature, no flag needed\n\nString query = \"\"\"\n        SELECT *\n        FROM orders\n        \"\"\";\n```\n\n**Rule of thumb:** text blocks are available unconditionally in Java 15+;\nif your codebase targets Java 15 or higher you should use them freely\nfor all multi-line string content.\n",12,null,{"description":11},"Java text blocks interview questions — triple-quote syntax, incidental whitespace stripping, line endings, escape sequences, formatted() method, and comparing text blocks to string concatenation and heredocs.","java\u002Fmodern-java\u002Ftext-blocks","Modern Java","modern-java","2026-06-20","01Xl11eivLS_NDw9BhLS7TxxvE-5YEhzNT9TbxQxKXw",[82,86,89,93,94,98,102,106],{"subtopic":83,"path":84,"order":85},"Records","\u002Fjava\u002Fmodern-java\u002Frecords",1,{"subtopic":87,"path":88,"order":12},"Sealed Classes","\u002Fjava\u002Fmodern-java\u002Fsealed-classes",{"subtopic":90,"path":91,"order":92},"Switch Pattern Matching","\u002Fjava\u002Fmodern-java\u002Fswitch-pattern-matching",3,{"subtopic":6,"path":21,"order":20},{"subtopic":95,"path":96,"order":97},"instanceof Pattern Matching","\u002Fjava\u002Fmodern-java\u002Finstanceof-pattern-matching",5,{"subtopic":99,"path":100,"order":101},"Virtual Threads","\u002Fjava\u002Fmodern-java\u002Fvirtual-threads",6,{"subtopic":103,"path":104,"order":105},"Record Patterns","\u002Fjava\u002Fmodern-java\u002Frecord-patterns",7,{"subtopic":107,"path":108,"order":109},"Sequenced Collections","\u002Fjava\u002Fmodern-java\u002Fsequenced-collections",8,{"path":111,"title":112},"\u002Fblog\u002Fjava-text-blocks","Java Text Blocks — Multi-line Strings Without the Escape Clutter",1782244117617]