In this first chapter from the book The Art of Java by Herbert Schildt and James Holmes, the authors highlight certain features of the Java programming language that separate it from other languages. The chapter also covers: memory management, Java's built-in support for multithreading, Java's approach to exceptions as compared to C++, Java's support of polymorphism, and how bytecode enables Java's "Write Once, Run Anywhere" ability and provides security. (ISBN 0-07-222971-3, McGraw-Hill/Osborne, 2003).
Despite all of its powerful features, Java may not have been much more than a footnote in programming history if it were not for one important but nearly transparent part of the language: bytecode. As all Java programmers know, the output of the Java compiler is not machine code that can be directly executed by a CPU. Instead, it is a highly optimized set of portable instructions, called bytecode, which are executed by the Java Virtual Machine (JVM). The original JVM was simply an interpreter for bytecode. Today, the JVM also applies on-the-fly compilation of bytecode into executable code. Whatever process is used to execute bytecode, its advantages are enormously important to the success of Java.
The first advantage is portability. By compiling a Java program into bytecode, it can be executed on any computer, with any type of CPU (and operating system) as long as a JVM is available for that environment. In other words, once a JVM has been implemented for a specific environment, any Java program can run in that environment. It is not necessary to create a separate executable for each different environment. The same bytecode can be run in all environments. Therefore, through the use of bytecode, Java offered programmers the ability “to write once, run anywhere.”
The second advantage achieved by bytecode is security. Because execution of the bytecode is under the control of the JVM, the JVM can prevent a Java program from performing malicious acts that affect the host machine. The ability to ensure the security of the host computer was crucial to the success of Java because it enabled the creation of the applet. Because an applet is a small, dynamically downloaded program that comes across the Internet, some mechanism to prevent applets from doing harm was necessary. The combination of bytecode and the JVM provided the mechanism by which applets could be downloaded safely. Frankly, without bytecode, the Web would be a much different place today.
Remember: this is chapter one of The Art of Java, by Herbert Schildt and James Holmes (McGraw-Hill/Osborne, ISBN 0-07-222971-3, 2003). Check it out at your favorite bookstore today. Buy this book now.