1. Overview

String formatting and generating text output often comes up during programming. In many cases, there is a need to add a new line to a string to format the output.

Let’s discuss how to use newline characters.

2. Adding Newline Characters in a String

Operating systems have special characters denoting the start of a new line. For example, in Linux a new line is denoted by “\n”, also called a Line Feed. In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF.

Adding a new line in Java is as simple as including “\n”* , “*\r”, or “\*r\n”* at the end of our string.**

2.1. Using CRLF Line-Breaks

For this example, we want to create a paragraph using two lines of text. Specifically, we want line2 to appear in a new line after line1.

For a Unix/Linux/New Mac-based OS we can use “\n”:

String line1 = "Humpty Dumpty sat on a wall.";
String line2 = "Humpty Dumpty had a great fall.";
String rhyme = line1 + "\n" + line2;

If we are on a Windows-based OS, we can use “\r\n”:

rhyme = line1 + "\r\n" + line2;

For an old Mac-based OS, we can use “\r”:

rhyme = line1 + "\r" + line2;

We’ve demonstrated three methods of adding a new line, but unfortunately, they’re platform dependent.

2.2. Using Platform Independent Line Separators

We can use system defined constants when we want our code to be platform independent.

For example, using System.lineSeparator() for giving a line separator:

rhyme = line1 + System.lineSeparator() + line2;

*Or we could also use System.getProperty(“line.separator”):*

rhyme = line1 + System.getProperty("line.separator") + line2;

2.3. Using Platform Independent Newline Characters

Although line separators provide platform independence, they force us to concatenate our strings.

If we are using something like System.out.printf or String.format, then the platform independent newline character, %n, can be used directly within a string:

rhyme = "Humpty Dumpty sat on a wall.%nHumpty Dumpty had a great fall.";

This is the same as including System.lineSeparator() within our string, but we don’t need to divide the string into multiple parts.

3. Adding Newline Characters in an HTML Page

Suppose we are creating a string that is part of an HTML page. *In that case, we can add an HTML break tag 
.
*

We can also use Unicode characters “& #13;” (Carriage Return) and “& #10;” (Line Feed). Although these characters work, they don’t work exactly like we might expect them to across all platforms. Instead, it is better to use
for line breaks.

Additionally, we can use “\n” in some HTML elements to break a line.

Overall, these are the three methods of breaking a line in HTML. We can decide which one to use depending on the HTML tag we are using.

3.1. HTML Break Tag

We can use HTML break tag
to break a line:

rhyme = line1 + "<br>" + line2;

The
tag for breaking a line works in almost all HTML elements like ,

,

, etc. However, note that it does not work in the