Check Java version in class files

Java classes can be compiled for different target platforms. You could e.g. compile with JDK 7 creating class files for Java 6. The target version is encoded in the beginning of the class files.

The major version of the different Java releases are:
Java 8 = 52 (0x34)
Java 7 = 51 (0x33)
Java 6 = 50 (0x32)
Java 5 = 49 (0x31)

So the class files for Java 6 starts with

0xCA 0xFE 0xBA 0xBE 0x00 0x00 0x00 0x32

We can use the following command to find e.g. all Java 6 classes.

find . -name \*.class -exec grep -P "^\xca\xfe\xba\xbe\x00\x00\x00\x32" {} \;

Or better still, just checking first line:
find . -name \*.class -exec sh -c 'head -1 {} | grep -P "^\xca\xfe\xba\xbe\x00\x00\x00\x32" {}' \;

However, it might be more interesting to find if any of the files we compile is NOT Java 6. This might happen when compiling with JDK 7, but forgetting to set Java 1.6 as target.

find . -name \*.class -exec sh -c 'head -1 {} | grep -v -q -P "^\xca\xfe\xba\xbe\x00\x00\x00\x32" && echo "Java version is not 0x32 in file {}" &' \;