Print newline in Java

In this post, we will explore how to print newline in Java.


 

A newline (aka end of line (EOL), line feed, or line break) is used to signify the end of a line and the start of a new one. Different operating systems use different notations for representing a newline using one or two control characters. On Unix/Linux and macOS systems, newline is represented by "\n"; on Microsoft Windows systems by "\r\n"; and on classic Mac OS with "\r".

 

1. Using platform-dependent newline character

The commonly used solution is to use platform-dependent newline character. For instance, "\n" on Unix and "\r\n" on Windows OS. The problem with this solution is that your program will not be portable.

 

Download   Run Code

 

2. System.getProperty()

The recommended solution is to use the value of the system property line.separator which returns the system-dependent line separator string. Since its value depends on the underlying OS, your code will be portable (platform independent).

 

Download   Run Code

 

3. System.lineSeparator()

Another solution is to use the built-in line separator lineSeparator() provided by the System class. It simply returns the value of the system property line.separator.

 

Download   Run Code

 

4. Using %n newline character

Another plausible way of getting the platform’s preferred line separator is to use the platform-independent newline character %n with printf() method.

 

Download   Run Code

 

5. System.out.println()

If we need a newline at the end of the string, we should call println() method which outputs newline character appropriate to your platform.

 

Download   Run Code

 

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
henry
Guest

awesome