Last updated May 8, 2024

How to quickly switch between Java 11, Java 8 and OpenJDK versions

This article explains how to configure the terminal of mac/unix based systems to quickly change the JAVA_HOME variable to point to a specific version of java.

This allows you to easily switch between Oracle Java 8, Oracle Java 11 or Adopt OpenJDK 8 for example.

Please note, you should ensure that the Atlassian server product you're intending to start using AMPS / Atlassian Plugin SDK is compatible with the Java version you've selected (via the Supported Platforms page).

Note that this only works for the current terminal tab/window and does not persist across sessions.

Step 1: Copy the following functions into ~/.bash_profile

1
2
# Function to switch JDK versions
function setjdk() {
    echo "Select the java version you wish to switch to from the following:" 
    echo 
    options=()
    count=-1

        while IFS= read -r line
        do
            if [[ ! "$line" == M* ]] && [[ ! "$line" == /* ]] && [[ ! -z "$line" ]]; then
                options+=("$line")
                ((count++))
                echo '['"$count"']'${options["$count"]}
            fi
        done < <(/usr/libexec/java_home -V 2>&1)

    echo 
    read -p "Please chose a value from the options above: " selectedOption </dev/tty
    
    if [ "$count" -ge "$selectedOption" ] && [ "$selectedOption" -ge '0' ]; then
        removeFromPath '/System/Library/Frameworks/JavaVM.framework/Home/bin'
        removeFromPath "$JAVA_HOME/bin"
        stringArray=(${options["$selectedOption"]})
        export JAVA_HOME="${stringArray[@]: -1}"
        export PATH="$JAVA_HOME"/bin:$PATH
        echo "JAVA_HOME is set to be ${JAVA_HOME}"
    else
        echo "Invalid option, JAVA_HOME was not set"
    fi
}

function removeFromPath() {
  export PATH=$(echo $PATH | sed -E -e "s;:$1;;" -e "s;$1:?;;")
 }

Step 2: Save the file and open a new terminal window

Once the above mentioned functions have been added to ~/.bash_profile all newly opened terminal windows will be able to directly call them.

Step 3: Running the function

Run the setjdk function by typing:

1
2
setjdk

You should see a list of installed java versions and be prompted to select one. The following image shows the selection of Java SE 8 on a system with three different java versions installed:

1
2
Select the java version you wish to switch to from the following:

[0] 1.8.0_192, x86_64: "AdoptOpenJDK 8" /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
[1] 1.8.0_191, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home
[2] 1.7.0_80, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home

Please chose a value from the options above: 1
JAVA_HOME is set to be /Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home

Additional Resources

Need help? Request support at Developer Technical Support Portal

Rate this page: