Java Text Blocks

Profile picture for user arilio666

Java text blocks, or multi-line string literals, are a  feature that came along in Java 15 that provides a more concise and readable way to represent multi-line strings in Java code. Text blocks are designed to write and manipulate multi-line strings such as SQL queries, JSON, XML, HTML, and other text-based data.
However, this is a preview feature in Java 15, meaning we won't know when it will leave.
Preview features should be enabled to use this.

String myText = """
   John, 
   Wick!
   """;
    
  • myText is a multi-line string that contains three lines of text. 
  • The leading and trailing quotes (""") indicate the beginning and end of the text block, and the text inside the text block is preserved exactly as it appears, including leading whitespaces.

Example:

  • Text Blocks can be used instead of a string literal to enhance visibility, clarity, and code readability.
  • We can do this when we have to use strings with multi lines.

Before Text Block:

String address = "18, crescent street, new york sanctum,\n" +
     "2, ny,\n" +
     "ch49ad";
      
  • Here we can see multi-line using double quotes before text block arrival.
String message = """
   18, crescent street, new york sanctum,
   2, NY,
   ch49ad""";
    
  • Using text block, we can see clearly how it is super readable.
String info = """
   Name: Monkey D Luffy
   Age: 26
   Welcome to The Grand Line!
   """;
System.out.println(info);

Output:

Name: Monkey D Luffy
Age: 26
Welcome to The Grand Line!
Tags