isJavaVersionAtMost()
is a SystemUtils
class that is used to check whether the Java version running in the system is, at most, the required version passed as an argument.
SystemUtils
The definition of SystemUtils
can be found in the Apache Commons Lang
package, which we can add to the Maven project by adding the following dependency to the pom.xml
file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the
commons-lang
package, refer to the Maven Repository.
You can import the SystemUtils
class as follows:
import org.apache.commons.lang3.SystemUtils;
public static boolean isJavaVersionAtMost(final JavaVersion requiredVersion)
final JavaVersion requiredVersion
: This is the required version of Java.
JavaVersion
is an enum representing all the versions of the Java specification.
This method returns true
if the actual version of the system is less than or equal to the required version. Otherwise, it returns false
.
import org.apache.commons.lang3.JavaVersion;import org.apache.commons.lang3.SystemUtils;public class Main{public static void main(String[] args){// Example 1JavaVersion javaVersion = JavaVersion.JAVA_17;System.out.println("The current version of Java in the system is - " + System.getProperty("java.specification.version"));System.out.println("----------");System.out.printf("The output of SystemUtils.isJavaVersionAtMost() when the version '%s' is required - '%b'", javaVersion, SystemUtils.isJavaVersionAtMost(javaVersion));System.out.println();// Example 2javaVersion = JavaVersion.JAVA_9;System.out.printf("The output of SystemUtils.isJavaVersionAtMost() when the version '%s' is required - '%b'", javaVersion, SystemUtils.isJavaVersionAtMost(javaVersion));}}
java version in the system = 11
required java version = 17
The method returns true
because the required version 17 is a greater version than 11.
java version in the system = 11
required java version = 9
The method returns false
because the required version 9 is a lesser version than 11.
The output of the code is as follows:
The current version of Java in the system is - 11
----------
The output of SystemUtils.isJavaVersionAtMost() when the version '17' is required - 'true'
The output of SystemUtils.isJavaVersionAtMost() when the version '9' is required - 'false'