Skip Top Navigation Bar

Formatting Output and Using Text Blocks

Overview

In this lesson, students will learn how to format console output.

Learning Objectives

Skills

Student Outcomes

Students will be able to:

Duration: 1 class period

Resources

Background

There are different ways to format program output.

Escape Sequences

Sometimes we want to print out characters that already have a specified meaning in a String literal. For example, the double quote is used at the start and end of a String literal, so how do we let the compiler know that we want to print the double quote instead of simply ending the String literal? We use an escape sequence. An escape sequence is comprised by a backslash (\) followed by a character. The backslash tells the compiler to treat the next character as special. The following is a list of some common escape sequences you might find useful.

Escape Sequence Explanation Example Example Result
\n Creates a new line characater "line one\nline two"

line one

line two

\" Inserts a double quote character in text "She said, \"Hi\"" She said, "Hi"
\' Inserts a single quote character in text "She\'s Great!" She's Great!
\\ Inserts a backslash character in text "Use a / for division not a \\" Use a / for division not a \
\t Creates a tab characater "column one\tcolumn two" column one   column two

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.

println("""
first
second
third""");

This is the same as:

println("first\nsecond\nthird");

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

println("""
first
second
third
""");

This is the same as:

println("first\nsecond\nthird\n");

A new line character is required after the opening three double quotes. The following will cause an error:

println("""first
second
third
""");

Activity

Activity 1: Escape Sequence Practice

Provide students with different layouts to print text. Some examples:

Activity 2: Create Character Art

Have students get creative and design a logo using only symbols, no use of letters or numbers.