How to get the current Java version at runtime in Java
Overview
There are two ways to obtain the JVM version at runtime in Java:
- Use the system property
java.version. - Use the
version()method of theRuntimeclass in Java.
java.version system property
A system property is a key-value pair that stores properties specific to the current system.
The java.version system property provides the JVM in use.
Code
In the below code, we print the current Java version using the java.version system property. We access the value of the property using the getProperty method of the System class.
public class Main {public static void main(String[] args){System.out.println("Current JVM version - " + System.getProperty("java.version"));}}
Runtime.version() method
version is a static method of the Runtime class that returns the current JVM version in use. This method was introduced in Java version 9.
Code
We print the current Java version using the Runtime.version() method in the below code.
public class Main {public static void main(String[] args){System.out.println("Current JVM version - " + Runtime.version());}}