Purpose for .class files in Java

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.


  1. The .class file is machine-readable. The machine that reads it is the Java Virtual Machine, which interprets it and compiles it to native code (executable by your computer).

  2. You don't need the .java files to run Java code. The .class files are all you need.