6

Im trying to switch the java version with the following

export JAVA_HOME='/usr/libexec/java_home -v 1.8.0_172'

but when I run java -version I got the following

java version "10.0.1" 2018-04-17 Java(TM) SE Runtime Environment 18.3 (build 10.0.1+10) Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.1+10, mixed mode)

I want to switch to the 1.8.0_172 version in MAC how it can be done ?

  • 2
    Possible duplicate of [How to set or change the default Java (JDK) version on OS X?](https://stackoverflow.com/questions/21964709/how-to-set-or-change-the-default-java-jdk-version-on-os-x) – lakshman Oct 02 '18 at 15:27
  • @lakshman It looks like the OP is already trying to apply the solutions of that question. – Mark Rotteveel Oct 02 '18 at 15:29
  • 1
    @MarkRotteveel: No He doesn't. OP uses quotes instead of backticks and there are other answers as well. – lakshman Oct 02 '18 at 15:35
  • 2
    @lakshman I said trying, and most other answers there are variations on that theme. I think it would have been helpful to point out that mistake initially (as it is non-obvious to people not familiar with bash). – Mark Rotteveel Oct 02 '18 at 15:38

4 Answers4

8

Assuming you have jdk1.8.0.172 installed, one option is:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/Contents/Home

mantithetical
  • 1,755
  • 2
  • 16
  • 21
  • 1
    to see the java versions you have available: `ls /Library/Java/JavaVirtualMachines/` – A H Jan 21 '21 at 14:12
6

I think the easiest for me was using jenv

It is similar to rvm or nvm to easily switch between java versions.

Steps:

brew install jenv

Bash

echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.bash_profile

echo 'eval "$(jenv init -)"' >> ~/.bash_profile

Zsh

echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.zshrc

echo 'eval "$(jenv init -)"' >> ~/.zshrc

In the terminal run unset JAVA_TOOL_OPTIONS (This is a precautionary measure in case you have output that breaks the text parsing. In my case this did make a difference)

jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_231.jdk/Contents/Home

jdk1.8.0_231.jdk -> Use whatever version you have on your machine.

Then use javac -versionto verify it has been changed.

D'Ante Barnes
  • 121
  • 2
  • 2
4

The above worked for me (removing quotes) with Mac OS Catalina, however I also had to set the path variable like below:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/{java version.jdk}/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH

Where {java_version.jdk} was any of the Java version listed after running

/usr/libexec/java_home -V 
Pelonomi Moiloa
  • 516
  • 5
  • 12
2
/usr/libexec/java_home -V

The above command will give you all java versions installed in your system.

export JAVA_HOME=`/usr/libexec/java_home -v <VERSION YOU WANT TO USE FROM ABOVE LIST`>
Madhurish Gupta
  • 216
  • 2
  • 3