Background
As stated in earlier post that java in a compiled as well as interpreted language.So now lets look how this works.To understand this well lets take an example.Lets say you created a file called Foo.java which has the class Foo in it.When you compile the file using javac Foo.java what if formed is another file called Foo.class. Do not worry about the syntax mentioned above at this point.This post is meant only to make you understand how Java works internally. Compilation and execution of Java programs will be dealt in upcoming posts.
So this Foo.class file created on compilation of Foo.java is nothing but what we call java bytecode.This bytecode can then be interpreted by Java interpreter present in the JVM.These class files are generally packaged and distributed as jar(Java ARchive) files.
Why do we need this "bytecode"?
The answer is very simple - platform independence.Lets say you have written a code in C, compiled it on one particular architecture say x86.The program may run fine on this architecture but for other architectures the program may fail.
In case of java this intermediate code called bytecode is the result of compilation of java code.This bytecode can then be run on any machine with any architecture. All it needs is a JVM to interpret the bytecode.The Java byte code cannot be directly executed on hardware the way that
compiled C code can. Instead the byte code must be interpreted by the
JVM (Java Virtual Machine) at runtime in order to be executed.
Java seeks to find a compromise between a purely compiled language (with
no portability) and a purely interpreted language (that is
significantly slower). By operating this way, Java gets some of the benefits of compiled
languages, while also getting some of the benefits of interpreted
languages. However, it also inherits some limitations from both of
these languages.
Diagrammatic Representation-
Sum it up
To run a Foo.java class you typically do -
- javac Foo.java
- java Foo
To sum it up this is what happens. javac is a compiler that essentially compiles you java files to class files containing byte codes. Now bytecodes is something any machine with a JVM installed can understand. Hence the - "Write once run everywhere" slogan. Class files (could be packaged in Jar) can now run on any machine of any operating system and architecture as long as it has a JVM. JVM know how to read and execute these bytecodes.
So how does it do it actually? That's the 2nd part of it. java program is an interpreter that interprets and executes byte codes by converting it into machine code.
There is also something called JVM hotspot and JIT (Just in time compilation). What happens in this is JVM maintains a count of time a routine is executed. If it exceeds a certain threshold then it is directly compiled into machine language and thereafter used directly to execute code (no need of interpretation).
No comments:
Post a Comment