Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose for .class files in Java

I am trying to understand how .class files work in java and what's their purpose. I found some information online, but I get unsatisfying explanations.

As soon as we run the compiler we get the .class file, which is bytecode. Is this machine readable or not? And if not, this is why we need the interpreter for the program to run successfully?

Also, since the .class file is the equivalent of our .java programs, why can't somebody run a java program straight away by just running the .class file using VM and they would need to have the .java file as well?

like image 283
aKid Avatar asked Mar 29 '14 15:03

aKid


1 Answers

The JVM is by definition a virtual machine, that is a software machine that simulates what a real machine does. Like real machines it has an instruction set (the bytecodes), a virtual computer architecture and an execution model. It is capable of running code written with this virtual instruction set, pretty much like a real machine can run machine code.

So, the class files contain the instructions in the virtual instruction set, and it is capable of running them. For that matter, a virtual machine can either interpret the code itself or compile it for the hardware architecture it is currently running. Some do both, some do just one of them (e.g. .net runtime compiles once the first time the method is called).

For instance, the Java HotSpot initially interprets bytecodes, and progressively compiles the code into machine code. This is called adaptive optimization. Some virtual machines always compile to machine code directly.

So, you can see there are two different "compiling concepts". One consists in the transformation of Java code to JVM bytecodes (From .java to .class). And a second compilation phase happens when the program runs, where the bytecodes may either be interpreted or compiled to actual machine code. This is done by the just-in-time compiler, within the JVM.

So, as you can see, a computer cannot run a Java program directly because the program is not written in a language that the computer understands. It is written in lingua-franca that all JVM implementations can understand. And there are implementations of that JVM for many operating systems and hardware architectures. These JVMs translate the programs in this lingua-franca (bytecodes) for any particular hardware (machine code). That's the beauty of the virtual machine.

like image 163
Edwin Dalorzo Avatar answered Oct 01 '22 01:10

Edwin Dalorzo