How to Add a Line to a String in Java


In this example we will show how to add a new line to a string. It makes use of escape character n, and the system.lineseparator () method.

Source Code

1)

package com.beginner.examples;

public class AddLineInString {

	
	public static void main(String[] args) {
		
		//The String will be displayed on one line
		String nums  = "one two three four five";
		
		System.out.println(nums);
		
		//'n' is an escape character
		//Add a new line
		String addLinenums = "onentwonthreenfournfive";
		
		System.out.println(addLinenums);

	}

}

Output:

one two three four five
one
two
three
four

2)

package com.beginner.examples;

public class AddLine2 {

	public static void main(String[] args) {

		// New rows can be obtained using the system.lineseparator () method, regardless
		// of the System
		String addLine = "0 1 2 3" + System.lineSeparator() + "4 5 6 7";

		System.out.println(addLine);
	}

}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments