I want to print \n.
String text = "";
text = "\n is used for new line";
but the \n is not showing when I run the code. How to do this?
I want to print \n.
String text = "";
text = "\n is used for new line";
but the \n is not showing when I run the code. How to do this?
If you want to actually write the two chars \
and n
to output, you need to escape the backslash: \\n
.
All escape sequences are listed in the documentation: https://docs.oracle.com/javase/tutorial/java/data/characters.html
You can also use System.lineSeparator()
, introduced in Java 8:
String result = "cat" + System.lineSeparator() + "dog";
System.out.print(result);
Output:
cat
dog
In java, the \
char is an escape character, meaning that the following char is some sort of control character (such as \n \t or \r).
To print literals in Java escape it with an additional \
char
Such as:
String text = "\\n is used for a new line";
System.out.println(text);
Will print:
\n is used for a new line