Tutorial to change Java versions in Apple macOS!

Note: I split this tutorial into 2 sections.  If you already know what JDKs are on your machine and where to locate them, look at "The Short" section.  Or else please follow "The Long" section for a more complete step-by-step tutorial to set things up.

The Short

Add the following aliases to your .bash_profile and then reload.  Update the name of the JDK accordingly.  Add additional aliases if you have other Java versions.

alias java_8="export JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home; java --version;"
alias java_12="export JAVA_HOME=/Library/Java/JavaVirtualMachines/openjdk-12.0.1.jdk/Contents/Home; java --version;"

The Long

Finding the Java libraries

1.) Open the terminal and use the following command to show which Java versions are installed on your Mac:

/usr/libexec/java_home -V

2.) Next, you'll see a list of Java versions.  Note the paths to the "Home" directory for each Java version because we will be using that to create aliases.

Adding the aliases

1.) Open the terminal and use the following command to ensure you're in your home directory on macOS:

cd ~

2.) Open up .bash_profile by using the following command.  If .bash_profile doesn't exist, it will still open a file called .bash_profile that will continue to exist once it's saved.

vim .bash_profile

3.) Press the key, "i", to be in insertion mode in Vim.  

4.) Add the following lines to the end of the file:

alias java_8="export JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home; java --version;"
alias java_12="export JAVA_HOME=/Library/Java/JavaVirtualMachines/openjdk-12.0.1.jdk/Contents/Home; java --version;"

5.) Then press the ESC (escape) key to get out of insertion mode in Vim.

6.) Next, press the colon key (SHIFT + semicolon) and type "wq" like the following while in Vim:

:wq

 7.) Now, press ENTER to run the command from the previous step to save the file and quit out of Vim.

8.) Now, run the following command to reload .bash_profile:

source ~/.bash_profile

9.) You should be ready to switch Java versions as needed in the terminal! Test it out to see if it works by running one of the alias commands like so:

 

Hopefully the tutorial was easy to follow and now you have a way to switch Java versions for your development needs!  Please contact me if you have any questions.  Thanks!

Tags