a shot of dev knowledge

RELATED TAGS

What is SystemUtils.isJavaVersionAtLeast() in Java?

Overview

isJavaVersionAtLeast() is a staticdescribes the methods in Java that can be called without creating an object of the class method of the SystemUtils class that is used to check whether the Java version running in the system is at least the required version passed as an argument.

How to import 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;

Syntax


public static boolean isJavaVersionAtLeast(JavaVersion requiredVersion)

Parameters

  • JavaVersion requiredVersion: The required version of Java.

JavaVersion is an enum representing all the versions of the Java specification.

Return value

This method returns true if the actual version of the system is greater than or equal to the required version. Otherwise, it returns false.

Code

import org.apache.commons.lang3.JavaVersion;
import org.apache.commons.lang3.SystemUtils;

public class Main{

    public static void main(String[] args){

        // Example 1
        JavaVersion 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.isJavaVersionAtLeast() when the version '%s' is required - '%b'", javaVersion, SystemUtils.isJavaVersionAtLeast(javaVersion));
        System.out.println();

        // Example 2
        javaVersion = JavaVersion.JAVA_9;
        System.out.printf("The output of SystemUtils.isJavaVersionAtLeast() when the version '%s' is required - '%b'", javaVersion, SystemUtils.isJavaVersionAtLeast(javaVersion));
        
    }
}

Example 1

  • java version in the system = 11
  • required java version = 17

The method returns false because version 11 is a lesser version than 17.

Example 2

  • java version in the system = 11
  • required java version = 9

The method returns true because version 11 is a greater version than 9.

Expected output

The output of the code is as follows:


The current version of Java in the system is - 11
----------
The output of SystemUtils.isJavaVersionAtLeast() when the version '17' is required - 'false'
The output of SystemUtils.isJavaVersionAtLeast() when the version '9' is required - 'true'

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring