EN
Java - get version programmatically (at runtime)
6 points
In this article, we would like to show how to get Java version programmatically.
Quick solution:
xxxxxxxxxx
1
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.
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:
xxxxxxxxxx
1
package com.example;
2
3
public class Program {
4
5
public static void main(String[] args) {
6
7
System.out.println(VersionUtils.getVersion());
8
}
9
}
Example output:
xxxxxxxxxx
1
17
Where: java.version
values was 17.0.6
.
VersionUtils.java
file:
xxxxxxxxxx
1
package com.example;
2
3
import java.util.regex.Matcher;
4
import java.util.regex.Pattern;
5
6
public class VersionUtils {
7
8
private static final Pattern PATTERN = Pattern.compile("^(\\d+)(?:\\.(\\d+))?");
9
10
private static int version = -1;
11
12
public static int getVersion() {
13
if (version != -1) {
14
return version;
15
}
16
String text = System.getProperty("java.version");
17
Matcher matcher = PATTERN.matcher(text);
18
if (matcher.find()) {
19
String major = matcher.group(1);
20
if ("1".equals(major)) {
21
String minor = matcher.group(2);
22
if (minor == null) {
23
version = 1;
24
} else {
25
version = Integer.parseInt(minor);
26
}
27
} else {
28
version = Integer.parseInt(major);
29
}
30
}
31
return version;
32
}
33
}