switch both java path and JAVA_HOME env at once
# switch java path
sudo alternatives --config java
# set JAVA_HOME
JAVA_HOME=$(java -jar printjavahome.jar)
export JAVA_HOME
echo "JAVA_HOME=${JAVA_HOME}"
echo ""
or set an alias in .bashrc
alias setjavahome='JAVA_HOME=$(java -jar printjavahome.jar) && export JAVA_HOME'
which is equivalent to
alias setjavahome='JAVA_HOME=$(readlink -f $(which java) | sed s/\\/bin\\/java$//) && export JAVA_HOME'
You can run PrintJavaHome.java without compilation with JDK 11+
$ java src/main/java/com/github/tkote/javahome/PrintJavaHome.java
There is a jshell version
$ $JAVA_HOME/bin/jshell printjavahome.jsh