First of all check current java versions, run following command in the terminal
/usr/libexec/java_home -V
which will output something like the following:
Matching Java Virtual Machines (2): 9, x86_64: "Java SE 9" /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home 1.8.0_152, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home
Choose the version you want to be the default (1.8.0_152 for example) then put following in to your .bash_profile:
export JAVA_HOME=/usr/libexec/java_home -v 1.8.0_152
Also you can specify just the major version, if it's unique, like:
export JAVA_HOME=/usr/libexec/java_home -v 1.8
export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)
Now when you check
java -version
you will got following output:
java version "1.8.0_152" Java(TM) SE Runtime Environment (build 1.8.0_152-b16) Java HotSpot(TM) 64-Bit Server VM (build 25.152-b16, mixed mode)