How to print \ n in a string in java

I want to print \ n.

String text = ""; text = "\n is used for new line"; 

but \ n is not displayed when I run the code. How to do it?

+7
java
source share
4 answers

Escape \ using \

 text = "\\n is used for new line"; 
+8
source share

If you want to write two characters \ and n for output, you need to avoid the backslash: \\n .

All escape sequences are listed in the documentation: https://docs.oracle.com/javase/tutorial/java/data/characters.html

+5
source share

In java, the \ char character is an escape character, which means that the next char is a kind of control character (e.g. \ n \ t or \ r).

To print literals in Java, run it with an extra \ char

For example:

 String text = "\\n is used for a new line"; System.out.println(text); 

It will be printed:

\ n is used for a new line

+1
source share

You can also use System.lineSeparator() introduced in Java 8 :

 String result = "cat" + System.lineSeparator() + "dog"; System.out.print(result); 

Output:

 cat dog 
+1
source share

All Articles