Java Text blocks

www.la‮uttu‬ri.com
Java Text blocks

Java text blocks are a new feature in Java 14 that allows you to define multi-line string literals in a more convenient way. Prior to Java 14, you would have to use the escape character (\) to denote a new line in a string literal, which can make the code difficult to read and maintain.

With text blocks, you can define a multi-line string literal by enclosing it in triple double quotes ("""). You can then format the string as you like, with line breaks and indentation, and the text block will preserve the formatting when it is compiled and used in your program.

Here's an example of a text block in Java:

String html = """
    <html>
        <body>
            <p>Hello, World!</p>
        </body>
    </html>
""";

Text blocks can be particularly useful when working with large blocks of text, such as HTML or XML, as they make it easier to read and maintain the code.

It's important to note that text blocks are not the same as raw string literals, which were introduced in Java 13. Raw string literals do not interpret escape sequences and can span multiple lines, but they do not preserve line breaks and indentation.

Created Time:2017-10-17 20:18:52  Author:lautturi