Java Articles

Advertisement

Determining Java Version

by Ram Satish

Share

In this example we will see how to determine the Java Runtime version. We will start with the system properties and then show you how one can determine the version by trying to classes that comprise the Java platform.

Find Java Version Using System Property or via JMX

System property java.version holds the Java Runtime Environment version. We can also determine the java jvm version/vendor or its specfication version and many other details using the managed bean for the runtime system of the Java virtual machine.
DetermineJavaVersion:

package com.javarticles.classloader;

import java.lang.management.ManagementFactory;

public class DetermineJavaVersion {
public static void main(String[] args) {
System.out.println("Java version=" + System.getProperty("java.version"));
System.out.println("Java version via JMX: " + ManagementFactory.getRuntimeMXBean().getSpecVersion());
}
}

Output:

Advertisement
Java version=1.8.0_25
Java version via JMX: 1.8

Determining Java version using ClassLoader

Each Java version introduces some new classes. We can try loading one of the newly introduced class and figure out whether it is of certain version or not.
For example, below we figure out whether the version is at least 5.

DetermineJava5OrPre5:

package com.javarticles.classloader;

public class DetermineJava5OrPre5 {
public static void main(String[] args) {
int javaVersion = 5;
try {
Class.forName("java.lang.annotation.Annotation");
System.out.println("Java version >= " + javaVersion);
} catch(Exception ex) {
System.out.println("Java version < " + javaVersion);
}
}
}

Determine whether Java version is at least 8.

Output:

Java version >= 5

DetermineJava7Or8:

package com.javarticles.classloader;

public class DetermineJava7Or8 {
public static void main(String[] args) {
int javaVersion = 7;
try {
Class.forName("java.util.stream.Collector");
javaVersion = 8;
System.out.println("Java version >= " + javaVersion);
} catch (Exception e) {
System.out.println("Java version = " + javaVersion);
}
}
}

Determine whether Java version is at least 9.

Output:

Java version >= 8

DetermineJava8Or9:

package com.javarticles.classloader;

public class DetermineJava8Or9 {
public static void main(String[] args) {
int javaVersion = 8;
try {
Class.forName("java.lang.reflect.InaccessibleObjectException");
javaVersion = 9;
System.out.println("Java version >= " + javaVersion);
} catch (Exception e) {
System.out.println("Java version = " + javaVersion);
}
}
}

Output:

Java version = 8

Download the source code

In this example, we have seen how to find the java version.

You can download the source code here: javadeterminingjavaversionexample.zip

Share

Advertisement

Related

Advertisement

Latest

Advertisement