Languages
[Edit]
EN

Java - get version programmatically (at runtime)

6 points
Created by:
daniell
490

In this article, we would like to show how to get Java version programmatically.

Quick solution:

String version = System.getProperty("java.version");

Warning: java.version may resturn string in format: 1.4.0, 1.4.2_42, 1.8.0, 11.0.18, 12, ..., 17.0.6, etc.

 

Major version

Early Java used 1.x versions format, later Java used x.x versions format, that makes necessary to distinguish exact major version. In this section you can find reusable util that lets to convert to proper major version, e.g. 17.0.6 to 17.

Note: to find available Java releases check this link.

Usage example:

package com.example;

public class Program {

	public static void main(String[] args) {

		System.out.println(VersionUtils.getVersion());
	}
}

Example output:

17

Where: java.version values was 17.0.6.

 

VersionUtils.java file:

package com.example;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VersionUtils {

    private static final Pattern PATTERN = Pattern.compile("^(\\d+)(?:\\.(\\d+))?");

    private static int version = -1;
	
	public static int getVersion() {
        if (version != -1) {
            return version;
        }
		String text = System.getProperty("java.version");
        Matcher matcher = PATTERN.matcher(text);
        if (matcher.find()) {
            String major = matcher.group(1);
            if ("1".equals(major)) {
                String minor = matcher.group(2);
                if (minor == null) {
                    version = 1;
                } else {
                    version = Integer.parseInt(minor);
                }
            } else {
                version = Integer.parseInt(major);
            }
        }
		return version;
    }
}

 

References

  1. JDK Releases

  2. Java version history - Wikipedia

Alternative titles

  1. Java - check version programmatically (at runtime)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join