27 May 2013

Difference between Byte Code and Class file


 when we compile a java source file it will be converted to a class file. The classes or interfaces written in the source file will be converted to bytecode and will be stored in the class file. The class file does not only contain byte code. It also contains some additional information which is useful to the compiler and virtual machine to compile and interpret the byte code.

For example when generic class is compiled the generic class will be converted to bytecode and will be stored in the class file. The byte code does not contain any information about generics but the class file which is generated from the source file does contain information about generics. This information is useful to the compiler when compiling other source files.

For Example:-

The source file which contains generic class:-
public class Person<T>{
   
       public T add(T a){
               System.out.println("happy");
       }
}


Generated Byte Code for the above class when compiled which is stored in the class file:-

public class Person{

         public Object add(Object a){
                    System.out.println("happy");
         }
}

The byte code will be stored in the class file and also the class file contains some additional information which is required by the compiler and virtual machine such as information about generics which are not really the part of Byte Code.

Generally VM need some additional information, which is usually stored at the top of the file (the file "header"), to know how to load and interpret the binary data in the file. Such header information could contain the generics details.

The process of erasing generics while compilation is called type erasure which is not very important to know in this context.
Post a Comment