Question #797   Submitted by Answiki on 11/03/2021 at 06:12:17 PM UTC

How to add carriage return in Java?

Answer   Submitted by Answiki on 11/03/2021 at 06:28:20 PM UTC

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");


2 events in history
Answer by Answiki on 11/03/2021 at 06:28:20 PM

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");


Question by Answiki 11/03/2021 at 06:12:17 PM
How to add carriage return in Java?
# ID Query URL Count

Icons proudly provided by Friconix.