Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile with java 6 from java 8 JDK installed

I am required to compile my source code with Java 6 for university. I currently have Java 8 JDK installed on my PC (Linux). How do I compile in Java 6?

p.s. I understand I wont be able to use any Java 7 or 8 features.

p.p.s. I realize java 6 source code will compile fine using the Java 8 JDK however I find that I am accidentally using post Java 6 features in my programs when compiling at home. When I try to compile the source code on the lab computers at uni I run into a bunch of errors. e.g. not being able to cast an object to a primitive.

like image 397
hcp Avatar asked Sep 15 '15 05:09

hcp


2 Answers

The way to fix that problem is to compile using the later SDK and use the cross compilation options when compiling.

Cross-Compilation Options

By default, classes are compiled against the bootstrap and extension classes of the platform that javac shipped with. But javac also supports cross-compiling, where classes are compiled against a bootstrap and extension classes of a different Java platform implementation. It is important to use the -bootclasspath and -extdirs options when cross-compiling.

-target version

Generates class files that target a specified release of the virtual machine. Class files will run on the specified target and on later releases, but not on earlier releases of the JVM. Valid targets are 1.1, 1.2, 1.3, 1.4, 1.5 (also 5), 1.6 (also 6), 1.7 (also 7), and 1.8 (also 8).

The default for the -target option depends on the value of the -source option:

  • If the -source option is not specified, then the value of the -target option is 1.8
  • If the -source option is 1.2, then the value of the -target option is 1.4
  • If the -source option is 1.3, then the value of the -target option is 1.4
  • If the -source option is 1.5, then the value of the -target option is 1.8
  • If the -source option is 1.6, then the value of the -target is option 1.8
  • If the -source option is 1.7, then the value of the -target is option 1.8
  • For all other values of the -source option, the value of the -target option is the value of the -source option.

-bootclasspath bootclasspath

Cross-compiles against the specified set of boot classes. As with the user class path, boot class path entries are separated by colons (:) and can be directories, JAR archives, or ZIP archives.

To use the options completely correctly (i.e. using also the -bootclasspath option) requires the rt.jar of a JRE (not JDK) of the target version.

like image 126
Andrew Thompson Avatar answered Sep 30 '22 09:09

Andrew Thompson


You can use the below for compilation

% javac -target 1.6 <whatever you want to compile>
like image 42
Kalyan Chavali Avatar answered Sep 30 '22 07:09

Kalyan Chavali