How to add carriage return in Java?
There are several ways to add a newline in Java. The first one is to use special characters \n
or \r
. The downside is that it's platform dependent:
- On Unix/Linux/Mac-based OS, use
\n
- On Windows-based OS, use
\r\n
- On old Mac-based OS, use
\r
String str1 = "On Linux\n";
String str2 = "On Windows\r\n";
You can use platform independent functions System.lineSeparator()
or System.getProperty("line.separator")
that will return the appropriate sequence to create a new line.
String str1 = "begin" + System.lineSeparator() + "end";
String str2 = "begin" + System.getProperty("line.separator") + "end";
The third option is to use platform independent newline character %n
. It can be used directly within a string, but must be formatted with System.out.printf
or String.format
.
String str = "begin %n end";
System.out.printf(str);
String str = String.format("begin %n end");
There are several ways to add a newline in Java. The first one is to use special characters \n
or \r
. The downside is that it's platform dependent:
- On Unix/Linux/Mac-based OS, use
\n
- On Windows-based OS, use
\r\n
- On old Mac-based OS, use
\r
String str1 = "On Linux\n";
String str2 = "On Windows\r\n";
You can use platform independent functions System.lineSeparator()
or System.getProperty("line.separator")
that will return the appropriate sequence to create a new line.
String str1 = "begin" + System.lineSeparator() + "end";
String str2 = "begin" + System.getProperty("line.separator") + "end";
The third option is to use platform independent newline character %n
. It can be used directly within a string, but must be formatted with System.out.printf
or String.format
.
String str = "begin %n end";
System.out.printf(str);
String str = String.format("begin %n end");
# | ID | Query | URL | Count |
---|