Following on from the previous article about the basic structure and syntax of Java, this article will explain what a .class file is and discuss how the Java Virtual Machine (JVM) enables developers to write code once and run it anywhere.
When you write a source code file, with the extension .java, you are writing code in a human readable format. Of course it helps if you know the Java language but, never the less, it is composed of characters and words that are familiar to us, presented in a logical easy to read layout. Consider the following code:
Even without knowing Java, you could hazard a good guess at what this code will do. However, the computer cannot read or run this file. In order for the computer to run your program it has to be compiled into something the computer can understand; Java byte-code. This can be done via the command line or as part of running a project using an IDE.
Compiling the .java file will create a .class file. This file contains the byte-code equivalent of your human readable Java source code. And it is this .class file that the computer can execute to run your java program. If you were to try to read the .class file you would see a string of characters that are much less human readable. For example, after compiling, opening the TimeWaster.class file in a text editor shows the following gobbledygook:
˛∫æ 4 " <init> ()V Code LineNumberTable LocalVariableTable this LTimeWaster; main ([Ljava/lang/String;)V args [Ljava/lang/String; SourceFile TimeWaster.java What a waste of time! ! TimeWaster java/lang/Object java/lang/System out Ljava/io/PrintStream; java/io/PrintStream println (Ljava/lang/String;)V ! / *∑ ± 7 ≤ ∂ ±
Sure there are some decipherable words in there, but it is not easy to read and would certainly be very difficult to write without making any mistakes!
Although it is the .class file that runs on your computer, it is not quite running on your computer in the same way that your operating system is running. In between your Java application (which is made up of .class files) and your operating system (which is running directly on your computer hardware) is another layer of software known as the Java Virtual Machine .
The JVM acts as an interface between your computer system and your Java classes and it is the JVM that is running your .class files. The beauty of this is that the Java code you write can run on any computer hardware and operating system without you, the developer, needing to know anything about the environment in advance.
Assuming that the target system has the Java runtime environment installed, Java is a write once deploy anywhere language. For example you can write a Java application and run that code on Windows, macOS or Linux without needing to make any changes to your source code for it to run on the target operating system. Click here for a more in depth understanding of the JVM.