Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JRE version must be equal to or above JDK version?

I've read that the bytecodes that the JDK generate are generic. What I say is that they only do things like memory mapping, calling, etc... So if that's true, it would mean that I can, for example, if write a program with characteristics of JDK 1.7, I don't need to worry about if it can run in a user with JRE 1.6? (It's an example, it could happen with more exagerated cases).

So, my question is: Can I write a program with new things from 1.7 and run it in 1.6?

like image 366
alesc3 Avatar asked Feb 15 '23 01:02

alesc3


2 Answers

Can I write a program with new things from 1.7 and run it in 1.6?

No. Java is not backward compatible.

Note that it is possible to create code compatible with a Java 1.6 JRE in a 1.7 JDK by using the cross-compilation options, but that code can only use the classes, attributes, methods and language features available in version 1.6.

like image 146
Andrew Thompson Avatar answered Feb 16 '23 14:02

Andrew Thompson


Can I write a program with new things from 1.7 and run it in 1.6?

The short answer is yes, but it is not officially supported. You'll have to resort to some hacks, but you can get it to work if you really want to. I wouldn't recommend doing this in a major project though.

In general bytecode is not backwards compatible because each classfile contains a version field. The JVM will refuse to run classes with a higher version than it was built for (lower versions are of course ok). By default, the javac that comes with Java 7 will create classes with version 51.0, which means they can only be executed by the JVM that comes with Java 7 or higher.

However, this doesn't mean it's impossible if you really want to create Java 6 compatible code. You can tell the compiler to generate classfiles with an earlier version. All this means is that you won't be able to use library and bytecode level features introduced in the new version.

Luckily, version 51.0 did not actually introduce any new bytecode features used by javac. All of the new features in Java 7 are implemented at compile time - the bytecode isn't any different except for the version! This means that any Java 7 class can be made to work as long as it doesn't rely on standard library updates (for example Try With Resources requires library support).

Unfortunately, javac refuses to compile Java 7 to version 50.0. But you can always change the bytecode version field yourself, either manually or with a tool. Since there were no new bytecode features, it will work just fine.

P.S. Memory mapping is down by the VM. There's no bytecode instructions for it. But you have the right idea.

like image 43
Antimony Avatar answered Feb 16 '23 15:02

Antimony