Tuesday, December 28, 2010

Have a Bite of Bytecode!!

This topic is very different from other Java topics.  I am sure a lot of developer think that why should I learn about byte code at all. Well I can give only two reasons of that

(1)    Either you are a Byte code engineer for example using a library like BCEL which is used to change/enhance byte code generated by Java compiler.

(2)    You are passionate to learn thing under the hood (Under the hood is used mostly by Bill Venners a great writer of a great book Inside the Java Virtual machine worth reading it.)

What is byte code after all??

Just like C and C++ generates assembler code. Java compiler generates byte codes.  This byte code is used by JVM to perform instructions written by Programmer in Java language.

What byte code consists of?
Byte code is basically combination of instructions to be executed at run time by JVM. The main things byte code has:
Opcodes: Opcode is an instruction which will get executed by JVM at run time.
Information of reference to the objects
Information about the local variables

There is one command line tool given by sun which comes with Java installer. That command line tool is used to read byte codes generated by Java compiler. For Example we have following java code:

public class BiteOfByteCode{
   public void sayHello(String name){
      System.out.println(name);
   }
}

Read more: Cup of Java with Java