If you want to add a line break in your output string in your Java code, you can make use of the newline character java method from the System class called System.lineSeparator(),
Example 1: Java newline using System.lineSeparator()
public class JavaNewLineCharExample {
public static void main(String... args) {
String myString = "Hello" + System.lineSeparator() + "World!";
System.out.println(myString);
}
}
Output:
Hello
World!
Example 2: Using \r character
public class JavaNewLineCharExample {
public static void main(String... args) {
String myString = "Hello \r World!";
System.out.println(myString);
}
}
Output:
Hello
World!
Example 3: Using \n character
public class JavaNewLineCharExample {
public static void main(String... args) {
String myString = "Hello \r World!";
System.out.println(myString);
}
}
Output:
Hello
World!
Example 4: Using \r\n character
public class JavaNewLineCharExample {
public static void main(String... args) {
String myString = "Hello \r\n World!";
System.out.println(myString);
}
}
Output:
Hello
World!

Note: It is always better to use the example 1 approach of using System.lineSeparator() because it will use the new line character based on what platform you are using/executing the code, example 2, 3 and 4 are platform dependent.
Have Questions? Post them here!
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!