$show=/label

Java Add or Print Newline In A String

SHARE:

A quick guide on how to add a new line in java for string formatting to go to the next line.

1. Overview

In this tutorial, We'll learn how to add and print the new line to string formatting the text in a better way.

Formating strings and resulting in the text in a different format is often needed in java programming.

Let us focus on adding new line escape characters in java. Example programs on adding newline character to String and to HTML contents.

And also we will discuss What is the difference between \n and \r (\n vs \r)?

we have already discussed the difference between \n and \t

Java Add or Print Newline In A String



2. Adding Newline to String in Java


Every operating system has its own special escape sequence to depict the new line character.

New lines characters are different for the operating system. For example, Linux considers the new line character by \n which is sometimes called Line Feed(LF).

And in windows operating system considers the new line by the "\r\n" combination and this is called as Carriage Return and Line Feed(CRLF).

It is possible to add the new line character escape sequences such as "\n", "\r" and "\r\n" in the string at any index or at the end of the string.

2.1 Using \n and \r Line Breaks


We can use these line breaks in the strings or can use to combine or mix strings with these escapes.

Let us see them with the related to the operating system.

Linux/Unix/mac os example

Create two strings and concat them with + operator along with the line breaks.
package com.javaprogramto.programs.escape.newline;

public class AddNewLineExample1 {

	public static void main(String[] args) {

		String line1 = "Hello engeers";
		String line2 = "hope you are staying safe";

		String line3 = line1 + "\n" + line2;

		System.out.println("Mac or unix or linux newline with \\n");
		System.out.println(line3);
	}
}

Output
Mac or unix or linux newline with \n
Hello engeers
hope you are staying safe

We can see that output string1 and string2 are separated with the new line.

Print newline character on windows operating system

we need to use the carriage return "\r\n" for accuracy.
package com.javaprogramto.programs.escape.newline;

public class AddNewLineExample2 {

	public static void main(String[] args) {

		// windows os
		String line1 = "Hello engeers";
		String line2 = "hope you are staying safe";

		String line3 = line1 + "\r\n" + line2;

		System.out.println("windwos print newline with \\r\\n");
		System.out.println(line3);
	}
}

Output
windwos print newline with \r\n
Hello engeers
hope you are staying safe

Print new lines in a string with old Mac OS 

Use just "\r" to print the new line in java.
package com.javaprogramto.programs.escape.newline;

public class AddNewLineExample3 {

	public static void main(String[] args) {
		
		// old mac os based
		String line1 = "Hello engeers";
		String line2 = "hope you are staying safe";
		
		String line3 = line1 + "\r" + line2;
		
		System.out.println("Old mac os print newline with \\r");
		System.out.println(line3);
	}
}


2.2 Use Sytem Depenent New Line Separtor


To make sure your code run always fine on any operating system, java provides a System API to add a new line independently from the java code.

This can be done in two ways as below.

a) System.lineSeparator()
b) System.getProperty()

System.lineSeparator() - Add new line example

How to add a new line with system class?
package com.javaprogramto.programs.escape.newline;

public class AddNewLineExample4 {

	public static void main(String[] args) {

		// Using java api system class lineSeparator() method
		String line1 = "Hello engeers";
		String line2 = "hope you are staying safe";

		String line3 = line1 + System.lineSeparator() + line2;

		System.out.println("print newline with System.lineSeparator() method");
		System.out.println(line3);
	}
}

This code works perfectly fine on any operating system.

Output
print newline with System.lineSeparator() method
Hello engeers
hope you are staying safe

System.getProperty() - Add new line example

Example With the system-level property and pass "line.separator" value to the getProperty() method. This method gets it from the system level environment variables.
package com.javaprogramto.programs.escape.newline;

public class AddNewLineExample4 {

	public static void main(String[] args) {

		// Using java api system class getProperty() method
		String line1 = "Hello engeers";
		String line2 = "hope you are staying safe";

		String line3 = line1 + System.getProperty("line.separator") + line2;

		System.out.println("print newline with System.getPropertyr() method");
		System.out.println(line3);
	}
}


Output
print newline with System.getProperty() method
Hello engeers
hope you are staying safe


2.3 Use Sytem InDepenent New Line Separtor


Apart from the system independent line separator to print new lines.

If you are not using the above two methods then whatever we use the line breakers are the system independent.

So, when you are using the system.out.printf()  or String.format() methods, then it is very convenient to include a line separator within the text rather than adding explicit concatenation.

Line separator with "%n" system dependent example
package com.javaprogramto.programs.escape.newline;

public class AddNewLineExample5 {

	public static void main(String[] args) {

		// Using system dependent %n
		String line1 = "Hello engeers%nwelcome to the java blog";

		System.out.println("print newline with %n line separator");
		System.out.printf(line1);
	}
}


Output
print newline with %n line separator
Hello engeers
welcome to the java blog

Note: %n line separtor will work with only printf() and String.format() methods.



3 Add Newline in Html Page


If you are constructing the Html tags within java code then you have three options to add the new blank lines.

3.1 Html Break tag
3.2 New line \n character
3.3 Unicode characters

ASCII code 13 corresponds to a Carriage Return (it's "\r").
ASCII code 10 corresponds to a Line Feed (it's "\n").

Example

The below example covers the different ways to add the new lines in Html tags.
package com.javaprogramto.programs.escape.newline;

public class AddNewLineExample6 {

	public static void main(String[] args) {

		// html break tag
		String tag1 = "<p>hello</p>";
		String tag2 = "<p>world</p>";

		String tag3 = tag1 + "</br>" + tag2;

		// using java \n
		String tag4 = tag1 + "\n" + tag3;

		// using unicodes

		String tag5 = "<p>This is paragraph text and 
 woops there is a new line.</p>";
	}
}


4. Difference between \n and \r


\n is represented as ASCII code 13 and \r is with ASCII code 10. These two lines represent the beaking of two lines but the operating system use them in a different way.

In Unix, only the \n char is enough to break the string into a new line but whereas in windows \r is followed by \n characters. So, the windows operating system needs two characters of an escape sequence.

While developing the java application and working with new line breaks you must have to take special care about them because these strictly follow the operating system rules.

It is always suggested to go with the OS-independent new lines with the use of System.lineSeparator() method. So, now you do not need to worry about OS related issues.


5. Conclusion


In this article, we've seen how to add new line breaks in strings and Html.



COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java Add or Print Newline In A String
Java Add or Print Newline In A String
A quick guide on how to add a new line in java for string formatting to go to the next line.
https://blogger.googleusercontent.com/img/a/AVvXsEh88Xx1jl60p0mASze76-L0vM3CW9aTb9t2uwB70Wc9yTk_dsqjAoqDCDpKity93WdDHt68Vv_D_9TOiva7NHXsMWdQcpmYrvNq2qSmkTstkTbw5G9VyyZ0o289bigNs_UYvDyegKtd8RG5Rt7csVKxB2w0nHbhNPSPI9xG8soSKOWjaevflqb9pb07=w640-h360
https://blogger.googleusercontent.com/img/a/AVvXsEh88Xx1jl60p0mASze76-L0vM3CW9aTb9t2uwB70Wc9yTk_dsqjAoqDCDpKity93WdDHt68Vv_D_9TOiva7NHXsMWdQcpmYrvNq2qSmkTstkTbw5G9VyyZ0o289bigNs_UYvDyegKtd8RG5Rt7csVKxB2w0nHbhNPSPI9xG8soSKOWjaevflqb9pb07=s72-w640-c-h360
JavaProgramTo.com
https://www.javaprogramto.com/2021/12/java-newline.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2021/12/java-newline.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content