EDIT: This answer is for the original question understood as
How come when I write Hello\nHello
in Java and then print it, I get two lines of text, but when I write Hello\nHello
in my terminal and pass it to my Java program as an argument, I get one line of text?
If you mean
Is there a way to pass one string argument to my java program which gets printed on multiple lines?
see @DodgyCodeException's answer, which is better suited to that formulation.
When you define a String
as "Hello\nHello"
in Java, it contains no '\'
character. It is an escape sequence for the line break: "\n"
is just one character.
When you use this string as an argument to your program, however (so the string is defined outside), "\n"
is interpreted as two characters: '\'
and 'n'
. You have to replace these two characters with the line break, knowing that to match '\'
you have to escape it with '\'
:
System.out.println(args[0].replace("\\n", "\n"));
For portability concerns, you can also use System.lineSeparator()
as the replacement string.