How to determine Java version from Program

By | February 14, 2021
How to determine Java version from Program

Introduction

Java has many versions so far, and with each version, some significant features are released. There are several differences between the APIs and how the code is written from version to version. That’s why to use some of the functionalities, we need to know which version our codebase is. For example, unboxing/boxing was introduced only in Java5, so if you are building an API that can be accessed by any Java code, old or new, you would probably make a check before performing some action.

How to determine Java version from Program

We have discussed above why it is important to determine the Java version. Java has a straightforward command for this:

Vamware
String whichVersion = System.getProperty("java.version");
System.out.println(whichVersion);

In my case, the version is: 1.5.0_12

The getProperty() method makes the JVM fetch property pertaining to the mentioned key from the Operating system.

If you use the method System.getProperties(), it returns all the properties listed in your OS in the Properties object. From the Properties object, you again have to use the method getProperty() along with the key (java.version) to get the java version.

You can also get the JVM version:

System.getProperty("java.vm.version");

This will fetch the result: 1.5.0_12-b04 for Java 5.

Since the output (version value) is a String, we can parse it any way we want. Like we mentioned in the introduction, we can make a check and write different code based on the java version:

if(whichVersion.startsWith("1.5")){
// some code
} else if(whichVersion.startsWith("1.2")){
// some other code
}

Conclusion

Knowing the JAVA version is helpful in cases when there are small bugs because of a version change. This helps save debugging time, and the issues can be easily fixed by putting the above check whenever required. The property key is the same in all machines like Windows or Mac, so you can try the code anywhere.

Leave a Reply

Your email address will not be published. Required fields are marked *