Friday, July 26, 2013

What's in .Class File

I never looked what's inside .class file except knowing that .class file consists of compiled byte code of Java Program. I was looking at quite a few articles, specifications, posts etc to get to know about byte class exact contents.
We already know what compiler does, what is a byte code, how byte code is executed by jre. Below is the brief definition.
Byte code: Java compiler (javac) generates the byte code for each Java file compiled. Byte-code is a sequence of mnemonics. Each of them will be translated by java run time environment to execute.
There are many mnemonics byte code consists of. Let's take a look at some of them with some examples which are very frequent.
Example 1:
package com.test;
public class Main
{
     public static void main(String...args)
     {
          System.out.println("Hello World");
     }
}
After compiling the Main.java, the generated class file looks like as below when you open in any hexa-decimal supported editor.




















To view the byte code in ASCII, we can use javap command.
Example: javap <class-name> displays the Class with methods in it where as -c option shows the each line of code inside the methods.












There are some basic points in the above lines of byte-code. As we know, each and every class we write, will be a sub-class of java.lang.Object ( as we can see extends java.lang.Object even we don't have that in .java file) and a default constructor is added with no parameters.
javap prints more detailed information
-s : the internal signature
-l : the line numbers and local variables used inside each function
And to print all the information, just give -verbose. Sample output looks like this

Interesting fact is, even though the java file is so simple with very few statements, compiler generated very large set of statements with tables, signatures, etc. We will see the details of few instructions in the next posts.