To add a line break, there are many methods in Java, such as the ālineSeparator()ā method, a newline character ā%nā, escape character, and many others. However, ā\nā is the most commonly used method for adding a line break.
This article will guide about \n and its usage in Java
What is \n in Java?
ā\nā is used to add a new line in text. It is also known as the End of Line or Line Break. \n is a platform-dependent line separator as on Windows systems, the newline is represented by “\r\n“; on Mac OS with “\r“, Unix/Linux, and macOS systems, the new line is represented by “\n“.
In Java, \n and \t are also called the Escape Characters or Escape Sequences. In these characters, a character is preceded by a backslash (\), containing letters, numbers, punctuation, and other symbols such as [\n, \t, \r, \ā, \] and so on.
Now, letās check out some examples related to using \n in a Java program.
Example 1
In this example, we will call System.out.println() method two print two Strings, āHelloā and āWorldā and add a concatenation operator ā+ā between them. As a result, the invoked method will print as a single string; however, we want to print it in two different lines as separate Strings.
To do so, we will add a line break using ā\nā between both strings:
The given output indicates that we have successfully added a line break with the help of \n:
Example 2
In this example, we have three Strings āaā, ābā and ācā having the following values:
It is required to concatenate āaā and ācā Strings and then print the value of ābā in the next line. To achieve this, we will add the ā\nā line break before concatenating the last String:
As you can see, the desired output is displayed with the usage of \n line break:
We presented all the essential information related to what is \n in Java.
Conclusion
ā\nā is an Escape Character in Java that is used to enter a new line in the output. It is also known as the end of line or line break. It is a platform-dependent line separator, mostly used to break a line because of its easy syntax. It helps the programmers to increase the readability of code. In this article, we explained what is \n in Java and its use with the help of suitable examples.