Java utility to get class version compiled for

Want to check out what is the Java class version compiled for, here comes several ways.

1) javap tool comes along with JDK/JRE
Assume you have a source code with compiled version of Test.class.
Open your terminal, type
In Unix:
javap -verbose Test | grep "version"
In Windows:
javap -verbose Test | find "version"

Note down Major version number.

Refer to this table:

Major Minor Java Platform Version
45 3 1.0
45 3 1.1
46 0 1.2
47 0 1.3
48 0 1.4
49 0 1.5
50 0 1.6
51 0 1.7
52 0 1.8

2) DataInputStream

There is another clever guy on StackOverFlow just read Java byte class into DataInputStream, and getting the magic number directly yield the minor and major. I copied the code here.

DataInputStream in = new DataInputStream(new FileInputStream(filename));
int magic = in.readInt();
if(magic != 0xcafebabe) {
	System.out.println(filename + " is not a valid class!");;
int minor = in.readUnsignedShort();
int major = in.readUnsignedShort();
System.out.println(filename + ": " + major + " . " + minor);

3) Unix od
Just below the Java code, other guys found a Unix command line to get the magic number.

od -x HelloWorldJava.class |head -2

I ran this code on my box I found:

od -x Test.class | head -2
0000000      feca    beba    0000    3400    0f00    000a    0003    070c
0000020      0d00    0007    010e    0600    693c    696e    3e74    0001

feca beba is a magic number, 0000 3400 represents Java SE 8.

Check it out my Java version:
java -version

java version "1.8.0_05"
Java(TM) SE Runtime Environment (build 1.8.0_05-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.5-b02, mixed mode)

What’s use for this check?

I experienced to maintain some legacy code on my box, with my Eclipse set to higher Java JDK version, when deploy to production server it encountered error showing something like “unrecognized class file version”. By using this check I can check the existing java class version on the server, and then go back to my Eclipse and adjust up/down (most probably down) my Java JDK version and compile a new one against it.

Author: fyhao

Jebsen & Jessen Comms Singapore INTI University College Bsc (Hon) of Computer Science, Coventry University

Leave a Reply