← All articles
Backend1 min read

Text Blocks and Modern String Methods

Escaping quotes and concatenating multi-line strings is a thing of the past. Text blocks and new String methods make Java text handling pleasant.

S

Swapnika Voora

Author

Embedding JSON or SQL in Java used to mean a mess of \n and +. Text blocks give you readable multi-line literals, and modern String methods handle the common chores.

Multi-line literals

A text block preserves formatting and strips the common leading whitespace based on the closing delimiter.

Query.java
String json = """
    {
      "id": %d,
      "status": "active"
    }
    """.formatted(id);

Handy String methods

strip, isBlank, lines, and repeat cover cases that used to need helpers.

Strings.java
"  hi  ".strip();            // "hi", Unicode-aware
"\n\t".isBlank();            // true
"a\nb\nc".lines().count();   // 3

Takeaways

  • Text blocks are ideal for SQL, JSON, and HTML snippets.
  • Use formatted to interpolate values into a block.
  • Prefer strip over trim for correct Unicode whitespace handling.

Add a trailing \ inside a text block to suppress the newline at that line, useful for long single-line strings you want to wrap in source.

#java#strings#language-features

More in Backend