Java

What is \n in Java

Web developers and programmers commonly create text-based output and format strings. They always break up their statements within multiple lines. If the output is not formatted correctly, the readability of the code will be affected.

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:

System.out.println("Hello" + '\n' + "World");

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:

String a = "Hello";

String b = "Enjoy";

String c = "World";

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:

System.out.println(a + c + '\n' + b);

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.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.