2

I am fairly new to Java and I was wondering why Java uses a virtual machine (the java program) to execute code after it has been compiled (by javac) unlike C.

535441434B
  • 273
  • 1
  • 18

4 Answers4

5

JAVA is 'Write Once Run Anywhere'

Check the link,It will make you clear about the whole process on which java works How is Java platform-independent when it needs a JVM to run? After the compilation,the code actually have to go through an intermediate state that is called as the bytecode.This bytecode is then taken up by the JVM present on the machine and then is converted into the form that is executable by the machine.enter image description here

The JVM for every different platform is different,But the bytecode generated by the compiler is same everytime.The JVM performs the function of handling the bytecode and producing executable code in the form as is understood by the platform on which you are working on.This is the reason that java is called as "Write Once Run Anywhere".

Community
  • 1
  • 1
nobalG
  • 4,544
  • 3
  • 34
  • 72
  • do you know what parts of the code/libraries run on machine code on the JVM? "API calls" so to speak. or how to word that question – gia Feb 19 '17 at 08:28
  • @gia jre (Java run time environment) ....google it – nobalG Feb 20 '17 at 11:17
3

Java Virtual Machine helps to keep the compiled code platform independent. With no intermediate platform, you would have to compile the code for each platform separately, however with JVM you only compile it once and let the appropriate JVMs handle the execution.

Warlord
  • 2,798
  • 16
  • 21
  • Ah, I see! Books, article, internet and... literally everything tells us that Java is 'WORA' when learning about Java. I guess I have to read this book more thoroughly! – 535441434B Feb 16 '14 at 11:42
3

Java code is compiled in multiple stages. The javac validates the code, but the JIT turns it into native code based on how the program is used and the platform it is running on. This allows the program to use the exact chipset of the process or used, rather a lowest common denominator for all the platforms it might need to run on.

With Java you can take an open source library which was compiled on 32-bit windows platform 10 years ago and deploy it on a 64-bit Linux server and it will not only work but be optimised for your latest CPU and the way you use it.

It is very common to develop Java applications on Windows and deploy it to a Linux system with different processor family without having to recompiling or worry about cross platform issues.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
3

It is for the portability issues. Java code can run on any machine in which JVM is installed. Basically JVM makes a optimized machine code which is dependent on machine on which code is running.

unknown
  • 241
  • 4
  • 16