Skip Top Navigation Bar

Formatting Output with Text Blocks

There are different ways to format program output. In this tutorial, we will explore using escape sequences and text blocks to format output.

Text blocks

Text blocks were introduced in JDK 15. If you are not running a version of Java that 15 or higher, you will not be able to use text blocks in your program code.

A text block is a multi-line String literal that avoids the needs for most escape sequences, automatically formats the string in a predictable way, and gives you control over the format when desired.

Text blocks start with three double quotes (""") on a line by itself. The content of the String literal begins at the first character on the next line and ends at the last character before three double quotes that are used to end the text block.

The following is an example of using a text block. This example can be put into the Java Playground or in the body of a main method if you are using an IDE.

Your Turn

Example 1

  • Predict the output of the code segement.
  • Check your prediction by running the code.
  • Modify the code to use the \n character to produce the same result.

Example 2

  • Predict the output of the code segment.
  • How does this code different from Example 1 above?
  • Modify the code to use the \n character to produce the same result.

Moving the closing three double quotes to the next line, will add another new line character at the end of the output.

Example 3

  • A new line character is required after the opening three double quotes.
  • Run the code below.
  • Modify the code to correct the error.

Resources

Next Learn Tutorial