In Java, compiled .class files contain a version number that corresponds to the Java version used to compile them. This major version number is crucial for ensuring compatibility between the compiled class files and the Java Virtual Machine (JVM) that executes them. Understanding these version numbers helps us troubleshoot class version errors and manage Java application compatibility effectively.
Table of contents:
- Java Class File Format
- List of Java Class File Major Version Numbers
- How to Check a Class File Version
- Common Class Version Errors
- Conclusion
- References
Java Class File Format
Every Java class file begins with a magic number (0xCAFEBABE) followed by the class file version (major and minor version numbers). The JVM uses these version numbers to verify if it can load and execute the class.
List of Java Class File Major Version Numbers
Below is a table of Java versions and their corresponding major version numbers:
| Java Version | Major Version |
|---|---|
| Java 1.1 | 45 |
| Java 1.2 | 46 |
| Java 1.3 | 47 |
| Java 1.4 | 48 |
| Java 5 | 49 |
| Java 6 | 50 |
| Java 7 | 51 |
| Java 8 | 52 |
| Java 9 | 53 |
| Java 10 | 54 |
| Java 11 | 55 |
| Java 12 | 56 |
| Java 13 | 57 |
| Java 14 | 58 |
| Java 15 | 59 |
| Java 16 | 60 |
| Java 17 | 61 |
| Java 18 | 62 |
| Java 19 | 63 |
| Java 20 | 64 |
| Java 21 | 65 |
| Java 22 | 66 |
| Java 23 | 67 |
| Java 24 | 68 |
| Java 25 | 69 |
How to Check a Class File Version
We can check the major version number of a .class file using the javap command-line tool:
javap
javap -verbose MyClass | findstr "major"
Example
javap -verbose com.mkyong.MainApp | findstr "major"
major version: 65
IN the above example, Java 21 (65) compiled the Java class.
Common Class Version Errors
If we see an error like:
Unsupported major.minor version 52.0
This means that the class file was compiled with Java 8 (major version 52), but the runtime environment is running an older version of Java that does not support it.
Solution
- Upgrade the JVM to a newer version that supports the class file version.
- Recompile the source code using an older Java version compatible with the target runtime using the
-sourceand-targetflags:
javac -source 1.8 -target 1.8 MyClass.java
Conclusion
Understanding Java class file major versions helps us troubleshoot compatibility issues and ensure smooth execution of Java applications. We should always ensure our runtime environment is compatible with our compiled class files.