Can program developed with Java 8 be run on Java 7?

Mitsu Garcia picture Mitsu Garcia · Mar 24, 2014 · Viewed 48.2k times · Source

I am a little confused.

  1. Oracle says Java 8 is highly compatible with Java 7 (backward). But, what possibilities exist that Java 8 program can be run on Java 7 successfully (SE/EE)?

  2. If point one was true, Java 8 applications will be deployed and executed on a Java 7 server support? for example, Tomcat 8 or WildFly?

Answer

Karol S picture Karol S · Mar 24, 2014

In general, no.

The backwards compatibility means that you can run Java 7 program on Java 8 runtime, not the other way around.

There are several reasons for that:

  • Bytecode is versioned and JVM checks if it supports the version it finds in .class files.

  • Some language constructs cannot be expressed in previous versions of bytecode.

  • There are new classes and methods in newer JRE's which won't work with older ones.

If you really, really want (tip: you don't), you can force the compiler to treat the source as one version of Java and emit bytecode for another, using something like this:

javac -source 1.8 -target 1.7 MyClass.java

(the same for Maven), and compile against JDK7, but in practice it will more often not work than work. I recommend you don't.

EDIT: JDK 8 apparently doesn't support this exact combination, so this won't work. Some other combinations of versions do work.

There are also programs to convert newer Java programs to work on older JVM's. For converting Java 8 to 5-7, you can try https://github.com/orfjackal/retrolambda To get lower than 5, you can pick one of these: http://en.wikipedia.org/wiki/Java_backporting_tools

None of these hacks will give you new Java 8 classes and methods, including functional programming support for collections, streams, time API, unsigned API, and so on. So I'd say it's not worth it.

Or, since you want to run your Java 8 JEE applications on an application server, just run your entire server on Java 8, it may work.