Java string new line
In Java, there are several ways to represent a new line in a string:
-
Using the newline character (
\n
): You can use the newline character (\n
) to represent a new line in a string. For example:String str = "Hello\nWorld";
This will result in a string that contains two lines: "Hello" and "World".
-
Using the line separator (
System.lineSeparator()
): You can use theSystem.lineSeparator()
method to get the platform-specific line separator, which is the character or sequence of characters used to separate lines in a text file. For example:String str = "Hello" + System.lineSeparator() + "World";
This will result in a string that contains two lines: "Hello" and "World", with the platform-specific line separator between them.
-
Using the
println()
method: You can use theprintln()
method to print a string to the console, followed by a newline character. For example:String str = "Hello"; System.out.println(str); System.out.println("World");
This will print "Hello" followed by a newline character, and then "World" followed by a newline character.
-
Using the
String.format()
method: You can use theString.format()
method to format a string with a newline character. For example:String str = String.format("Hello%nWorld");
This will result in a string that contains two lines: "Hello" and "World", with a newline character between them.
-
Using the
BufferedReader
class: You can use theBufferedReader
class to read a file line by line, and then concatenate the lines into a single string. For example:BufferedReader reader = new BufferedReader(new FileReader("file.txt")); String str = ""; String line; while ((line = reader.readLine())!= null) { str += line + "\n"; } reader.close();
This will read a file line by line, and then concatenate the lines into a single string with newline characters between them.
Note that the newline character (\n
) is platform-specific, and may not work correctly on all platforms. The System.lineSeparator()
method is a more reliable way to get the platform-specific line separator.