Java New Line


Java New Line: New line character in Java is a single character escape sequence denoted by \n as in C/C++. In println() method, the ln carries a new line implicitly.

Following is the very basic program you learnt where \n (Java New Line) is used.

public class Demo
{
  public static void main(String args[])
  {              
    System.out.println("Hello");
    System.out.println("World");
    System.out.println("way\njava");

    System.out.print("Java");   
    System.out.print("Sir");
  }
}

Java New Line

Hello and World are printed in different lines due to ln in println() method. way\njava prints in two lines due to \n. Java and Sir are printed in a single line due to no ln in print() (not println()).

Even though Java supports ln while printing at DOS prompt, still java supports \n. Two \n\n gives two new lines. This is not tried in the above program

To write a new line in a file, it is very different. To write a new line in the destination file in file copying, \n does not work. Here, we use the following.

String lineEnd = System.getProperty(“line.separator”);

Infact, new line character is operating system dependent. To know the new line character supported by the OS, use line.separator of getProperty() defined in System class. This is explained and used while file copying in DataInputStream and DataOutputStream – File Copying

Leave a Comment

Your email address will not be published.