Java Notes

System Independent Newline Characters

There are three different major systems for indicating the end of a line (new line): One for Unix, one for the Macintosh, and one for DOS/Windows.

Unix. The '\n' character represents the single Unicode character with the value 10 ('\u000A') and is used to separate lines in Unix files. This character is also sometimes called linefeed.

Windows. Windows programs often process a '\n' separated text file correctly (NotePad is a exception), but many expect a pair of characters (carriage return followed by line feed = "\r\n") Use the method below to get the newline string that is appropriate for your system.

Mac. In the past, the Apple Mac requirse lines to be separated by '\r', but their move toward Unix (System X) probably means they also accept '\n'. I haven't used a Mac in quite a while tho, so I'm not positive.

System independent value. You can get the value for the system your Java program is running on from the system properties. It is essential to do this with portable programs, and you should always assume your program is portable, eg, that it might run as an applet or using Webstart.

public static String newline = System.getProperty("line.separator");

When NOT to use the system independent newline characters

JTextArea lines should be separated by a single '\n' character, not the sequence that is used for file line separators in the operating system.

Console output (eg, System.out.println()), works fine with '\n', even on Windows.