Saturday, 16 August 2014

CAFEBABE - Print the magic number from Java class file

Isn't it interesting to know that Java class files have a 4 byte header which could be read as CAFEBABE in Hexadecimal. This is being mentioned in Wikipedia: Java class file.

Have you ever tried printing this secret code out? If not, let's do that.

Below is the code which reads it's own class file and prints the code to output stream.

 package com.javavirtues.cafebabe;  
 public class PrintHeader {  
      public static void main(String[] args) {  
           File classFile = new File(  
           if (classFile.exists()) {  
                System.out.println("Class file exists. Reading header.");  
                byte[] readHeader = new byte[4];  
                FileInputStream fileInputStream = null;  
                try {  
                     fileInputStream = new FileInputStream(classFile);  
                     for (byte readByte : readHeader) {  
                          System.out.printf("%02X", readByte);  
                } catch (IOException exception) {  
                } finally {  
                     if (fileInputStream != null) {  
                          try {  
                          } catch (IOException e) {  

You can download the eclipse project here.

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.