2️⃣

2.2 Formatting Text

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?
Click arrow for answer
First name: Jyoti Last Name: Rani
 
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?
Click arrow for answer
Hello world!    The ball dropped         down             down                 down
 
Let's break down the special characters above. The two that are used are:
  1. The newline character
  1. 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

Create a program called AboutMeVariables. Your program should store your name and any message you want in 2 variables. (Be sure to follow good naming conventions!) Then, use a single println statement to print your name followed by your message. Your message should be on the next line. (Hint: Use a newline character.)

Next Section

Chapter 2 Quiz
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.