JAVA_HOME and java_home on MacOS

02 Feb 2020

java-home is a nice util that helps to manage multiple java versions on you Mac.
It can be found at /usr/lib/exec/java_home
And I have no idea where it comes from (maybe it was installed with Oracle JDK or maybe it is some system util … who cares)

Have a look at what its help says:

/usr/libexec/java_home -h
Usage: java_home [options...]
    Returns the path to a Java home directory from the current user's settings.

Options:
    [-v/--version   <version>]       Filter Java versions in the "JVMVersion" form 1.X(+ or *).
    [-a/--arch      <architecture>]  Filter JVMs matching architecture (i386, x86_64, etc).
    [-d/--datamodel <datamodel>]     Filter JVMs capable of -d32 or -d64
    [-t/--task      <task>]          Use the JVM list for a specific task (Applets, WebStart, BundledApp, JNI, or CommandLine)
    [-F/--failfast]                  Fail when filters return no JVMs, do not continue with default.
    [   --exec      <command> ...]   Execute the $JAVA_HOME/bin/<command> with the remaining arguments.
    [-R/--request]                   Request installation of a Java Runtime if not installed.
    [-X/--xml]                       Print full JVM list and additional data as XML plist.
    [-V/--verbose]                   Print full JVM list with architectures.
    [-h/--help]                      This usage information.

Here how I use it:

1. Create some aliases in .bash_profile and call one of them:
   alias j8="export JAVA_HOME=`/usr/libexec/java_home -v 1.8`"
   alias j13="export JAVA_HOME=`/usr/libexec/java_home -v 13`"
   j13

2. Do not add $JAVA_HOME/bin to $PATH var, because your java is symlink to .../Commands/java which always checks $JAVA_HOME var
   which java
   > /usr/bin/java
   ls -al /usr/bin/java
   > /usr/bin/java -> /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java

3. Happy hacking!

Here some random guy has spent too much time with this primitive util, join him if you brave enough:
https://medium.com/notes-for-geeks/java-home-and-java-home-on-macos-f246cab643bd