0

I try to find a use case when it is necessary to use a special target version of the compiler javac using the target parameter.

Java is backward compatible, isn't it? So, if I compile a hello world program with version 11, it could run on a JVM with version 8, or?

The only use case I could imagine is, when you have dependencies (other jars) which are compiled in a certain version and you have to match this special version when compiling the own code.

halfer
  • 19,471
  • 17
  • 87
  • 173
mrbela
  • 4,156
  • 7
  • 42
  • 74

2 Answers2

3

Java is backward compatible, isn't it? So, if I compile a hello world program with version 11, it could run on a JVM with version 8

That is exactly backward. If you have a version of a Java class compiled with version 8, Java 11 is backwards compatible and can run it. The reverse is not backwards compatibility, and is the purpose of the --target command line flag. Specifically so a class compiled by the Java 11 compiler can run on Java 8. Without that, you would get an java.lang.UnsupportedClassVersionError: Unsupported major.minor version

Elliott Frisch
  • 191,680
  • 20
  • 149
  • 239
2

By default, classes are compiled against the bootstrap and extension classes of the platform that javac shipped with. But javac also supports cross-compiling.

-target version

Generate class files that target a specified version of the VM. Class files will run on the specified target and on later versions, but not on earlier versions of the VM. Valid targets are 1.1, 1.2, 1.3, 1.4, 1.5 (also 5), 1.6 (also 6), and 1.7 (also 7) ... . The default for -target depends on the value of -source:

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

Refer javadoc for more details here.

Dark Knight
  • 8,002
  • 4
  • 34
  • 56