Java is known as a platform independent language unlike C, C++. Now what makes Java a platform independent language? Unlike other programming languages output of Java compiler is not executable code rather it is a bytecode. Now what is this bytecode?
Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system. Java Run time system is called as JVM. JVM works as an interpreter for bytecode. So a Java program is first compiled by Java compiler and then interpreted by JVM. This processing can be clear with the following diagram:
In the above diagram, Java compiler converts .java file(source code) to .class file(bytecode) and then JVM which acts as a Java interpreter converts .class file(bytecode) to executable code(or machine code). Unlike other languages Source code is not directly compiled and converted into executable code. Java compiler first compiles the code and then interprets the bytecode and the finally generates the executable code.
Now what is the use of including this extra headache of converting to byte code?
The whole purpose is to make this language a platform independent language. This transalating a Java program into bytecode makes it much easier to run a program in a wide variety of environments. Only the JVM(whose purpose is to convert bytecode to executable code) needs to be implemented for each platform. Though the details of JVM differ from platform to platform. but they all still understand the same bytecode. This is the reason Java is a platform independent language and called "Write once, run anywhere & anytime".
I would also like to show you JVM Architecture to make things more clear:
Note: When we run Java program, JVM is loaded internally in memory and JVM in tun loads our Java application so Java do not have direct interaction with OS. Only JVM do the work of OS(Operation System) for Java program.
[ PS: Copied from Have Fun with Java :sshhh: ]
;) :p
-Feel free to fire questions.