Avoiding Platform Depedent Code

Although Java is considered platform independent (i.e. compiled Java code can execute on different operating systems without re-compiling), you can still write Java code that is platform dependent. The compiler won't complain when you write platform dependent code, but users on different system will not be happy when they try to run your program.

To ensure the staff can run and grade all your code, avoid the following platform dependence issues. You will be held responsible for all issues discussed on this page!



Windows and Unix systems use different characters to represent the start of a new line. In 6.005, we require that all required output for an assignment use the Unix newline character: '\n'.

This means if an assignment requires you to write to a file, you should make sure your program uses '\n' in the file. Do not worry about output you use for personal debugging.

You can ensure your program uses '\n' by setting the line.separator property. After setting this property, calls to methods like println() from PrintStream will use the value set for line.separator. Note, that System.out.println() will still use your system's default println. Do not worry about this.

PrintStream before, after;
// Creating printstream BEFORE setting property will NOT
// use the custom newline =(
before = new PrintStream( "foo.txt" );

// Setting system property for newline
System.setProperty( "line.separator", "\n" );

// Creating the printstream AFTER setting the property
// uses the custom newline =)
after = new PrintStream( "baz.txt" );

before.println( "This will NOT use the newline we set in the properties" );
after.println( "This will work as expected" );

Environment Variables

In Java, you can access environment variables using the System.getenv() method. You should avoid doing this if the same value is available in a system property. For example, if the operating system provides a user name, it will be in the system property user.name.

String username;

username = System.getenv( "USERNAME" );

// Better
username = System.getProperty( "user.name" );


Even when using Swing, there may be many subtle differences in the appearance of your UI on different platforms. Some general guidelines:


In Unix, attempting to bind a socket to a port less than 1024 will cause a permission exception in Java. Do not bind a socket to a local port below 1024.