Setting up Java on Mac
Polynomial Time
2 min read
You have to install Homebrew and Xcode command-line tools
I installed X-code Directly from Appstore
xcode-select --install
# I haven't tested this method but this should also work if you don't like installing from AppstoreTo Install homebrew copy and run a command: https://brew.sh/
Don't forget to add homebrew to the path
Installing and using one version of Java is easy using Homebrew when where it gets tricky is when managing multiple versions of java so for this I am going to leave all that hasel to a tool called jenv
#Setting up java
#Install version of java you want using homebrew
brew install openjdk@11
brew install openjdk@17
#Install Jenv
brew install jenv
#Set PATH
#-- for bash --
echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.bash_profile
echo 'eval "$(jenv init -)"' >> ~/.bash_profile
source ~/.bash_profile
#-- for zsh --
echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(jenv init -)"' >> ~/.zshrc
source ~/.zshrc
#to start using installed jdk add it to jenv
jenv add /usr/local/opt/openjdk@11
jenv add /usr/local/opt/openjdk@17
#This path can be different when homebrewed:
#ie: /opt/homebrew/opt/openjdk@11
#Check available java versions
jenv versions
#Set the default java version throught the system
jenv global 11
#Set version at some folder location
cd </folder/myproject/path>
jenv local 11
#Check java version
java --version # this should now show java 11
jenv doctor #check all verisons
#For me this was not setting JAVA_HOME value
ie : echo ${JAVA_HOME}
# DON't do this HACK : (Find the correct way)
#here what I did is explictly tried to set JAVA_HOME version to one that jenv sets
#This works but when u switch java version ie: jenv global 17 it does not work anymore
#Do i reverted this changes back by commenting below lines i used in first place
echo 'export JAVA_HOME=$(dirname $(dirname $(jenv which java)))' >> ~/.zshrc
echo 'export JAVA_HOME=$(dirname $(dirname $(jenv which java)))' >> ~/.bashrc
jenv doctor #check version's now
source ~/.bash_profile #So that it refreshes settings in current terminal session
source ~/.zshrc #So that it refreshes settings in current terminal session
d
0
Subscribe to my newsletter
Read articles from Polynomial Time directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by