Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Java version at runtime

Tags:

java

jvm

I need to work around a Java bug in JDK 1.5 which was fixed in 1.6. I'm using the following condition:

if (System.getProperty("java.version").startsWith("1.5.")) {
    ...
} else {
    ...
}

Will this work for other JVMs? Is there a better way to check this?

like image 429
list Avatar asked Oct 17 '22 02:10

list


People also ask

How do I find the Java version in runtime?

Use the system property java. version . Use the version() method of the Runtime class in Java.

Is Java version and JVM version same?

The java. vm. version is the jvm version number, something like "25.0-b70" whereas the java. version is the normal java language version you're used to seeing "1.8.

How do I set Java version from command line?

From a command line, type java -version to display the current jre version installed. With release 1.6, it's now possible to select a different JRE installation than the last one without any registry modification. It's probably the 1.6 JRE that will be used since it's the last installed.


1 Answers

java.version is a system property that exists in every JVM. There are two possible formats for it:

  • Java 8 or lower: 1.6.0_23, 1.7.0, 1.7.0_80, 1.8.0_211
  • Java 9 or higher: 9.0.1, 11.0.4, 12, 12.0.1

Here is a trick to extract the major version: If it is a 1.x.y_z version string, extract the character at index 2 of the string. If it is a x.y.z version string, cut the string to its first dot character, if one exists.

private static int getVersion() {
    String version = System.getProperty("java.version");
    if(version.startsWith("1.")) {
        version = version.substring(2, 3);
    } else {
        int dot = version.indexOf(".");
        if(dot != -1) { version = version.substring(0, dot); }
    } return Integer.parseInt(version);
}

Now you can check the version much more comfortably:

if(getVersion() < 6) {
    // ...
}
like image 147
Aaron Digulla Avatar answered Oct 19 '22 16:10

Aaron Digulla