Friday, July 18, 2014

Finding java version from .class file

Below are simple steps to find on what java version a .class file is compiled upon.

Every compiled class has major minor version put in by the compiler. The first 4 bytes of the class file is the magic number used to identify that it is class file format of java and magic number is 0xCAFEBABE.
The next 4 bytes of the file contains minor version followed by major version (each of 2 bytes).

The below are values used for identifying each version:

Java version
HEXA Decimal value
Decimal value
8
0x34
52
7
0x33
51
6
0x32
50
5
0x31
49
1.4
0x30
48
1.3
0x2F
47
1.2
0x2E
46
1.1
0x2D
45

 
JVM checks whether the class being executed is supported on the current version of JRE or not. If an error occurs about version mismatch it prints the value in DECIMAL and not in HEXADECIMAL .

For example:
If a java file compiled on JDK 5.0 is executed on a JRE of version lower than 5.0 then always the below error will occur (meaning the version number won’t change)
Unsupported major.minor version 49.0

Most simple of way checking the HEXA values of the magic and version numbers of the class file is to open in a text editor which supports HEXA mode and check for the major/minor version as show in the below screen shot.

From the above image it is clear that the Version of java on which the java file is compiled is JAVA 7 (0033 corresponds to Java 7 from the above table).

Refer JVM Specs in order to understand the JAVA class file format.