9

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?

Saeed ur Rehman
  • 727
  • 2
  • 10
  • 25
  • If you're planning on writing to the console, rather than using "print" use "println". That will give you your linebreak anyway. – durbnpoisn Nov 15 '15 at 20:49

4 Answers4

11

Escape the \ with \

text = "\\n is used for new line";
rajuGT
  • 6,224
  • 2
  • 26
  • 44
6

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

Kvam
  • 2,148
  • 1
  • 20
  • 32
5

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

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

Output:

cat
dog
Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
3

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

Andy Guibert
  • 41,446
  • 8
  • 38
  • 61