Java Compiler: how should Java language be mapped to JVM instructions?

Viewed 89

The semantics of constructs in Java language are defined by the Java language specification, but they're not in terms of JVM instructions. So, is there possiblity that the specification is not strictly defined to prevent mis-implementation of Java compilers? Or the mapping between Java language and JVM instructions is pretty straightforward, there's no need to worry about this?

2 Answers

It would defeat much of the point of separating the language from the bytecode for there to be a clear mapping of Java code to JVM instructions. Instead the compiler has the freedom to make determinations of which instructions best represent the provided source, in order to optimize the efficiency of what's actually run.

This does mean it's possible for a compiler to do the wrong thing, however generally speaking you can trust major compilers like Oracle's are doing the right thing; they get tested a lot.

The semantics of constructs in Java language are defined by the Java language specification, but they're not in terms of JVM instructions. So, is there possiblity that the specification is not strictly defined to prevent mis-implementation of Java compilers?

Yes, definitely. Later editions of the Java Language Specification use more formal notation than previous versions. This should help to reduce the possibility of ambiguity and misinterpretation, but any language specification primarily written in English is prone to misinterpretation.

Or the mapping between Java language and JVM instructions is pretty straightforward, there's no need to worry about this?

I think 'straightforward' is a subjective measure. :o) It's more straightforward than I first expected, certainly.

The compiler (javac) itself doesn't appear to do much in the way of optimisation, see this question for example. Most optimisations are actually done by the JVM at runtime (by HotSpot).

Other compiler implementations might do more optimisations. Also, there are some bytecode processors (like ProGuard) that perform optimisations on the bytecode.

Related