Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
1. Platform Dependent New Line Character
2.1.
Implementation in Java
2.2.
Java
2.3.
Output
2.4.
Adding Newline Characters in a String
2.4.1.
Using CRLF Line-Breaks
2.4.2.
Using Platform Independent Line Separators
2.4.3.
Using Platform Independent Newline Characters
2.5.
Adding Newline Characters in an HTML Page
2.5.1.
HTML Break Tag
2.5.2.
Newline Character
2.5.3.
Unicode Characters
3.
2. Using getProperty() Method
3.1.
Implementation in Java
3.2.
Java
3.3.
Output
4.
3. Using lineSeperator() Method
4.1.
Implementation in Java
4.2.
Java
4.3.
Output
5.
4. Using %n Character
5.1.
Implementation in Java
5.2.
Java
5.3.
Output
6.
5. Using out.println() Method
6.1.
Implementation in Java
6.2.
Java
6.3.
Output
7.
What is New Line In Java?
8.
Difference Between \n and \r
9.
Frequently Asked Questions
9.1.
What is \n in Java?
9.2.
How do you add a line break to a string?
9.3.
How to break the string into two lines Java?
9.4.
What is the \t character?
9.5.
What is nextLine () in Java?
9.6.
What is has next line in Java?
10.
Conclusion
Last Updated: Jun 11, 2024
Easy

Methods to Print New Line in Java

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Java is an object-oriented, class-based programming language. Java is a high-level programming language that generally emphasizes minimizing the number of implementation dependencies. Java is also a static and general-purpose programming language. It lets the users utilize the concept of write once and run anywhere (WORA). This means that the compiled code can be run on any system having the Java Virtual Compiler (JVM). The Java Virtual Machine or JVM is used to convert the code into a machine-understandable byte code. Now that we know a little about Java, let us discuss methods for adding a NewLine Character to a String in Java.

new line in java

In Java, adding a new line is as easy as adding "n", "r", or "rn" to the end of our string.

There are five methods to create a new line in Java:

  1. Platform-dependent newline character
  2. getProperty() method
  3. lineSeperator() method
  4. %n newline character
  5. out.println() method

1. Platform Dependent New Line Character

Each operating system has a unique character specified to create a new line. For instance, in Windows, we use “\n” to declare a new line. Since every operating system has a specific character for creating a new line, this code is platform dependent and may not work for other platforms. 

Implementation in Java

  • Java

Java

class codingNinjas{
public static void main(String args[]){
System.out.println("Hey Ninja"+"\n"+"Welcome");
}
}

Output

Output

Adding Newline Characters in a String

To show the start of the new line, OS(operating system) provides special characters. On a Linux machine, we can use Line feed(\n) to denote the new line. But in Windows, we can use Carriage return and Line feed(\r\n), it is also known as CRLF.

Using CRLF Line-Breaks

As we discussed before, we can use CRLF to add new line characters in a string. For example, we want to write two lines, one after the other. So, on Windows, we can do this by \r\n. 

String str1 = "Hello, Mr. Ninja";
String str2 = "How are you?";
String introOfNinja = str1 + "\r\n" + str2;

On Linux, we can write it as

String introOfNinja = str1 + "\n" + str2;

These methods are platform-dependent, that why we can go with other methods which are platform-independent.

Using Platform Independent Line Separators

When you want your code should be platform-independent, then you can use line separators. Let us consider the above example,

String str1 = "Hello, Mr. Ninja";
String str2 = "How are you?";
String introOfNinja = str1 + System.lineSeparator() + str2;

 

The System.lineSeparator() method returns the system-dependent line separator. By appending it between the strings, you can achieve line breaks that are appropriate for the current operating system.

Using Platform Independent Newline Characters

Line separators, while ensuring platform independence, necessitate string concatenation. When we employ methods like System.out.printf or String.format, the platform-independent newline character, %n, can be directly utilized within the string. For example, 

String introOfNinja="Hello, Mr. Ninja%nHow are you?";

Adding Newline Characters in an HTML Page

To add newline characters in an HTML page, you can use HTML tags or entities to represent line breaks. We can use a break tag(<br>), unicode characters carriage return("&#13") and line feed("&#10"). While these characters can be used, their behavior may not be consistent across all platforms. Therefore, it is recommended to use the <br> tag for line breaks as it provides more reliable and consistent results.

HTML Break Tag

We can use a break tag(<br>) to give line breaks. For example, there is a paragraph tag(<p>),

<p>Hello, Ninjas<br>How are you?</p>

<br> tag works with all the elements in HTML. But we cannot use it with <textarea> tag.

Newline Character

For <textarea> or <pre> tag, we can use the \n to give a break in the line. For example, 

<textarea>Hello Ninjas,\nWelcome to our platform.</textarea>

Unicode Characters

We can also use Unicode characters &#10; or &#13; to give a line break. For example,

<p>This is the first line.&#10;This is the second line.</p>

Here, the HTML entities &#10; or &#13; can be used to represent newline characters. &#10; represents a line feed (LF) character, while &#13; represents a carriage return (CR) character.

Also see, Nmap commands

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

2. Using getProperty() Method

This is a platform-independent approach in which we use the line.separator property. The line.separator property can be fetched using the getProperty() method. 

Implementation in Java

  • Java

Java

class codingNinjas{
public static void main(String args[]){
String createNewLine = System.getProperty("line.separator");
System.out.println("Hey Ninja"+ createNewLine +"Welcome" + createNewLine + "Creating a new line using the getProperty() Method");
}
}

Output

Output

You can also read about the topic of Java Destructor and Hashcode Method in Java.

3. Using lineSeperator() Method

This is yet another platform-independent approach to creating a new line in Java. In this approach, we directly use the lineSeperator function instead of passing it as an argument in the getProperty function. 

Implementation in Java

  • Java

Java

class codingNinjas{
public static void main(String args[]){
String createNewLine = System.lineSeparator();
System.out.println("Hey Ninja"+ createNewLine +"Welcome" + createNewLine + "Creating a new line using the lineSeparator() Method");
}
}

Output

Output

4. Using %n Character

Instead of using the platform-dependent characters, we can also use the “%n” character. The “%n” character is a platform-independent character. The “%n” character is used explicitly with the printf function instead of the commonly used println function.  

Implementation in Java

  • Java

Java

class codingNinjas{
public static void main(String args[]){
System.out.printf("Hey Ninja%nWelcome");
}
}

Output

Output

Must Read Type Conversion in Java

5. Using out.println() Method

The out.println() method automatically creates a new line in Java. It creates a new line after every sentence. 

Implementation in Java

  • Java

Java

class codingNinjas{
public static void main(String args[]){
System.out.println("Hey Ninja");
System.out.println("Welcome");
}
}

Output

Output

Try it on online java compiler. Now, let's discuss some frequently asked questions associated with the custom interceptors.

What is New Line In Java?

A newline (end of the line (EOL), line break) signifies the end of a line and the beginning of a new one. Operating systems use different characters to represent a newline: Unix/Linux and macOS use "\n", Windows uses "\r\n", and classic Mac OS uses "\r".

Difference Between \n and \r

There are some differences between \n and \r, let us understand them:

Parameters\n\r
MeaningIt means newline.It means carriage return.
RepresentationIt represents a line break.It does not create a line break.
UseIt moves the cursor to the next line.                      It simply returns the cursor to the start of the line.
ValueIts ASCII value is 10 (LF).Its ASCII value is 13 (CR).

Frequently Asked Questions

What is \n in Java?

In Java, \n is an escape sequence that represents a newline character. It is used to insert a line break or start a new line in strings or output. When the \n escape sequence is encountered in a string literal or a character literal, it is replaced by the actual newline character.

How do you add a line break to a string?

To add a line break to a string in Java, you can use the newline character (\n) within the string. For example, if we concatenate two strings along with \n, we will see a line break.

How to break the string into two lines Java?

To break the string into two lines in Java, we can use the substring() function to make parts and store them into two string variables. Then we can use the +(concat) operator to join them. For example, A+"\n"+B, where A and B are two parts of the string.

What is the \t character?

The `\t` character is a special code that represents a horizontal tab in text. It's used to create space or indentation between words or characters in a way that aligns them neatly.

What is nextLine () in Java?

nextLine() is a method in Java's Scanner class used to read the next line of input from the user or from a file, terminating only when it encounters a newline character.

What is has next line in Java?

hasNextLine() is a method in Java's Scanner class used to check if there is another line of input available to be read from the input source, returning true if such a line exists, otherwise false.

Conclusion

In this article, we have discussed methods to print new line in Java. Mastering the various methods to print new lines in Java is essential for effective programming and output formatting. From using escape sequences like \n to platform-independent approaches such as System.lineSeparator(), Java provides developers with flexibility and control over newline handling. 
Hey Ninjas! Don’t stop here. Check out Coding Ninjas for Java, more unique courses, and guided paths. Also, try Coding Ninjas Studio for more exciting articles, interview experiences, and excellent Machine Learning and Java problems.

Recommended Readings:

Previous article
Perfect Number in Java
Next article
System.out.println in Java
Live masterclass