What is SystemUtils.getJavaHome() in Java?

Overview

getJavaHome() is a staticthe methods in Java that can be called without creating an object of the class. method of the SystemUtils class that is used to return the Java home directory of the host system as an instance of the File class. The path to the Java home directory is stored as a system property under the name java.home.

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 File getJavaHome()

Parameters

The method accepts no parameters.

Return value

This method returns the File object pointing to the Java home directory.

Code

import org.apache.commons.lang3.SystemUtils;
import java.io.File;
public class Main{
public static void main(String[] args){
File javaHomeDir = SystemUtils.getJavaHome();
System.out.printf("The absolute path of the java home directory is '%s'.", javaHomeDir.getAbsolutePath());
}
}

In the code above, we use the getJavaHome() method to get the File object pointing to the Java home directory. Next, we print the absolute path of the Java home directory.

Output

The output of the code will be as follows:


The absolute path of the java home directory is '/Users/educative/Library/Java/JavaVirtualMachines/corretto-11.0.12/Contents/Home'.

Running the code above in your system can give a different output depending on your machine.

Free Resources