First search what is your current java version:
echo $JAVA_HOME
If java is already installed, the results will be a location like this:
/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home
In case, it is not you need to download the latest JDK (NOT JRE) (or the version required) and install that version (https://www.oracle.com/au/java/technologies/javase-downloads.html)
Now, change directory to JAVA_HOME one (a few levels up though)
cd /Library/Java/JavaVirtualMachines
You will be able to view all the JDKs installed here.
ls -al
Now to set, say the version 13.0.2, use the command
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-13.0.2.jdk/Contents/Home
For a permanent change of JAVA_HOME, add/update your .bash_profile
or .zshrc
/usr/libexec/java_home
is the simplest maintainable way of setting JAVA_HOME
on macOS.
export JAVA_HOME=`/usr/libexec/java_home -v 13`
Use the below command to find out all the versions of JAVA that are installed on this mac
/usr/libexec/java_home -V