Where is Java's home; what to set JAVA_HOME to

152 Views Asked by At

I am trying to run a JVM service and it needs JAVA_HOME set.

java is on my PATH, but it's not clear what JAVA_HOME should be set to:

which java
/usr/bin/java
1

There are 1 best solutions below

0
Darren Bishop On BEST ANSWER

While alternatives may remain popular on *nix systems, I mostly use jenv and occasionally sdkman; they all introduce a level of indirection, if /usr/bin/java was not obscure enough.

If you are happy with the version of java on your PATH (java -version), you can query java directly for java.home:

java -XshowSettings:properties -version |& grep -Po '(?<=java.home = )(.*)'

This is not available in Java 6:

docker run --rm openjdk:6 java -XshowSettings:properties -version
Unrecognized option: -XshowSettings:properties
Could not create the Java virtual machine.

It is available since Java 7:

docker run --rm openjdk:7 bash -c "java -XshowSettings:properties -version |& grep -Po '(?<=java.home = |java.home=)(.*)'"
/usr/lib/jvm/java-7-openjdk-armhf/jre

For ease of use, create an alias:

alias java_home="java -XshowSettings:properties -version |& grep -Po '(?<=java.home = |java.home=)(.*)' "

Alternatives:

jrunscript or jshell

Some distributions provide jrunscript or jshell; these can be used to run Java code as script:

jrunscript -Dpolyglot.js.nashorn-compat=true -e 'java.lang.System.out.println(java.lang.System.getProperty("java.home"));'

or

jshell -J-Dpolyglot.js.nashorn-compat=true - <<<'java.lang.System.out.println(java.lang.System.getProperty("java.home"));'

Note this approach and these tools are old and should be considered deprecated.

Java as a Source Interpreter

Since Java 11 you can execute Java source code as a script directly on the java binary:

cat <<EOF > ./java-home
#! /usr/bin/java --source 11

public class JavaHome {
    public static void main(String[] args) {
        System.out.println(System.getProperty("java.home"));
    }
}
EOF

chmod u+x ./java-home

./java-home
/usr/lib/jvm/java-11-openjdk-arm64