Saturday, March 06, 2021

System.out.println() vs. System.out.print("\n")

There is a subtle difference between these two statements

System.out.println()

and

System.out.print("\n")

Though on the surface they both seem to be doing the same thing and fact they are doing the same thing - print a new line to the console, there is a subtle difference between the two that is worth taking note of. 

System.out.print("\n"): Always prints "\n" to the console. This is the platform neutral way of printing a new line character to the console. 

System.out.println():  Prints platform specific new line character to the console, which is different for different OS. On windows, it prints "\r\n". On linux it prints "\n" and so on... 

This code demonstrates this

public class Main {

    public static void main(String[] args) {

        System.out.println();
        System.out.print("\n");
    }
}

It produces the below output on my windows laptop



System.out.println() is equal to System.out.print(System.lineSeparator()) - both of which produces the same output - printing platform specific new line character to the console

public class Main {

    public static void main(String[] args) {

        System.out.println();
        System.out.print(System.lineSeparator());
    }
}

This code produces the output for both the print statements




Sample code used in this post can be downloaded from https://github.com/ashokkumarta/awesomely-java/tree/main/2021/03/Curious-Cases/println()-vs.-print()

No comments:

Post a Comment