In: Computer Science
Explain how Java is both a compiled and interpreted language.
Hi,
Before getting into the question, let us first get clear with what exactly compiler and interpreter will do and what makes them different from each other.
A compiler is a computer program that converts the code written in high level programming language(like C,Java etc) into a machine code(binary i.e 0s and 1s) which computer can understand and process.
A interpreter is a computer program that converts high level programming statements into machine code(binary).
So now you might think both compiler and interpreter does the same thing. Yes, they both do the same thing but in a different way. While compiler compiles the code at once, an interpreter convers each high language statement one by one. Therefore compiler compiles the code before the execution of the program whereas interpreter conver the code into machine language during run time i.e during execution of the program.This makes comiplers work faster than interpreter.
Now that we understood the difference between a compiler and interpreter, let's get into our question. Is Java a compiler and interpreter language ?
The answer is Java is both compiler and interpreter language. The programming code written in java is saved as .java file . When a .java file is executed , javac a java compiler compiles the .java file into a byte-code . But this byte can't be executed by the cpu because it is not native code. Now, this byte-code is then converted to an machine code by the java interpreter called Java Virtual Machine(JVM). The JVM interpreted code is a binary code and can be executed by the CPU. Therefore Java is both a compiler and a interpreter language.
Now you might come across a question. What is the use of converting the .java file to an byte-code and then interpreting to a binary code which increase the execution time of the program when it can be converted directly to an binary code using just compiler which executes program quicker?
Here comes the java's magic. A java program unlike any other programs like C,C++ etc , can be run on any operating system without changing the code nor changing the type of compiler beacause of the byte-code generated by Javac(java compiler). The byte-code can be run on any kind of operating system without changing the code by using JVM on that system. This made Java very popular languange. A single can be used on multiple systems is made possible by java by using both compiler to convert the code to byte-code and allowing this byte-code to be used across a large variety of systems without any changes by using JVM.
Hope I have answered your question.
Thank you :)