Friday, March 20, 2009

New Line Character in Java for Windows and Linux.

As we all know, Java is a platform independent. But there may be some cases, when we will have to consider the platform. The new line character for Windows is CR + LF that mean Carriage Return and Line Feed. Its ASCII value is 13. But for Linux, it is '\n' and its ASCII value is 10. It might be different for MAC. So, we cannot be sure what to use for New Line in Java.

One alternative might be use System.out.println(""). But it increases code.

Another alternative might be defining a static variable as shown below.

private static final String NEWLINE = System.getProperty("line.separator");

Here, NEWLINE stores the actual String value of line separator character of the system. So, use of NEWLINE removes the platform dependency in this case. It can be used like this.

System.out.printf(NEWLINE + "  Total Department Salary: %.2f" + NEWLINE, salary);