Hi, you may have encountered the problem of having to use different java virtual machines in osx, either because apple currently installs jdk8 by default and you want to try jdk9 or jdk10, or because you want to compile something with openjdk or the official oracle jdk.
The fact is that I found a program, called jenv, also available for linux, which is responsible for setting the variable JAVA_HOME for you every time you want to use one or the other. A script could be used for this, but this solution is cleaner and as it is a brew application, every time you do a brew update, the application will be updated.
This is the link of the official project, have fun and peace!
You may have a look to this thread in Stackoverflow.