Chapter Table of Contents

Ch. 2 Output

Section Table of Contents

Newline and Tab

There are also some handy commands you can use for making your text look nice. Here are a few examples of the newline and tab characters.

public class FormattingText {
    public static void main(String[] args) {
        String firstName = "Jyoti";
        String lastName = "Rani";
        System.out.println(
            "First name: " + firstName + "\\nLast name: " + lastName
        );
    }
}

Newline example. The "\n" is computer-speak for "new line." What do you think will be printed out this time?

public class BallDrop {
    public static void main(String[] args) {
        System.out.println("Hello world!");
        System.out.println(
            "The ball dropped \\n\\t down \\n\\t\\t down \\n\\t\\t\\t down"
        );
    }
}

Tab character example. The "\t" is computer-speak for "tab." What do you think will be printed?

Let's break down the special characters above. The two that are used are:

  1. The newline character
  2. The tab character

The first character is the command for a new line. This is more convenient than typing out a new System.out.println every time you wish for a new line. The second character is for a tab, which is like an indentation. The syntax is a backslash + the letter (t or n). Notice how placing multiple tab characters next to each other increases the number of times of indentation.

Practice

About Me Variables