Thursday, February 14, 2013

Introduction to Java Bytecode

When you compile your Java applications, the Java compiler compiles your code down to Java bytecode that is run on the Java Virtual Machine (JVM). Java bytecode is similar to assembly language in its set of instructions. This is a very simple introduction to Java bytecode, along with an example of how a simple arithmetic expression will look when compiled down to bytecode. To keep this tutorial at a "bytecode 101" level, let's only focus on the following four bytecode instructions.
  1. ldc  integer-constant
  2. This instruction will push a constant integer value onto the stack.
  3. imul
  4. This instruction will multiply the top two integer values on the stack, replacing the two integers with the result of the multiplication operation.
  5. iadd
  6. This instruction will add the top two integer values on the stack, replacing the two integers with the result of the addition operation.
  7. isub 
  8. This instruction will subtract the top two integer values on the stack, replacing the two integers with the result of the addition operation.

Take the following arithmetic expression:

7 + 8 * 9 - 24

This expression will be compiled down to the following Java bytecode:

ldc   24
ldc   7
ldc   8
ldc   9
imul
iadd
isub

As you can see, the JVM places information and data onto the stack and performs stack operations on the information. Obviously, this is not a complete coverage of bytecode operations and the JVM, but I hope this helps provide a basic understanding of what Java bytecode looks like, while also showing how it works. In future tutorials, I'll provide more complicated examples. In the meantime, if you're interested in more information about the JVM and some of the optimizations it performs, read my blog post on JVM optimizations.

1 comment:

  1. Your blog has given me that thing which I never expect to get from all over the websites. Nice post guys!

    ReplyDelete