4 ways to add New Line Character to a String in Java

When you are required to output Strings with your Java code, more often than not, there is a requirement to format the output correctly. 

Adding a newline character between two strings in order to separate them, or create a paragraph is one of the most common requirements. Let's look at a few ways today, on how to output a newline between two Strings.

1. System.out.println inbuilt function

One of the easiest ways, is to use the function System.out.println(). The println() function will automatically add a new line to the output, if using two strings. 


String s1 = "This is a String.";
String s2 = "This is another String.";


If you don't want to use a separate System.out.println for every String, there are other ways as well. Read on!

2. Add a newline character "\n"

You can simply append newline character yourself to the strings, and use a single System.out.print command to print. 


String s3 = "This is a String.";
String s4 = "This is another String.";


3. Platform Independent Line separator

You can use Java inbuilt line separator function to insert a newline character. 


String s5 = "This is a String.";
String s6 = "This is another String.";

4. Add a newline character within a long string, without concatenation

If you have a single long String, and don't have to concatenate different strings, then also you can add a newline character. You can add %n, and then use String.format() function to format the String before printing it.

String s7 = "This is a really long string. I want to add a new line within the String itself.%nSee how I have managed to print to next line.";

Thanks for Reading the Article. If you have reached this far, we hope that the article was useful to you! Please Like/Share/Follow us on FacebookTwitterTumblr. 


Popular posts from this blog

Calculate Your CTC Salary Hike Percentage - Online Calculator to find your New Salary

Find the Longest Streak of 1's in a Binary Array using Java Code

Java Program to read Excel File and Load into Array

Java Program to Read a Properties file and return a Property Value

Create a File logging Utility using Java Code