[Java] Easily switch Java version with alias on macOS

less than 1 minute read

Configuration

Set an alias such as environment variables JAVA_HOME and PATH in .zshrc. Set for each installed Java Virtual Machine (JVM).

# AdoptOpenJDK 8
alias setjava8="export JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home; export PATH=/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/bin:$(echo $ {PATH})"

# AdoptOpenJDK 11
alias setjava11="export JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home; export PATH=/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home/bin:$(echo $ {PATH})"

# AdoptOpenJDK 14
alias setjava14="export JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-14.jdk-14.jdk/Contents/Home; export PATH=/Library/Java/JavaVirtualMachines/adoptopenjdk-14.jdk/Contents/Home/bin:$(echo $ {PATH})"

# Amazon Corretto 8
alias setcorretto8="export JAVA_HOME=/Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home; export PATH=/Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home/bin: $(echo ${PATH})"

# Zulu OpenJDK 13
alias setzulu13="export JAVA_HOME=/Library/Java/JavaVirtualMachines/zulu-13.jdk/Contents/Home; export PATH=/Library/Java/JavaVirtualMachines/zulu-13.jdk/Contents/Home/bin:$(echo $ {PATH})"

Switch Java version

Java version can be switched by inputting the set alias name.

$ setjava14

Check the environment variable and java -version to see if it has been switched.

$ echo; echo JAVA_HOME=${JAVA_HOME}; echo; echo PATH=${PATH}; echo; echo'java -version'; java -version

JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-14.jdk/Contents/Home

PATH=/Library/Java/JavaVirtualMachines/adoptopenjdk-14.jdk/Contents/Home/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr /bin

java -version
openjdk version "14.0.2" 2020-07-14
OpenJDK Runtime Environment AdoptOpenJDK (build 14.0.2+12)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 14.0.2+12, mixed mode, sharing)

Disadvantage

  • Since the environment variable PATH is expanded when setting an alias, the length of PATH set by the alias may be extended each time the shell is started.

Tags: ,

Updated: