How to change JAVA_HOME with a Bash script
When you are executing a script, you are creating a new process off the interactive shell that lives for the length of your script.

By default this child process inherits your interactive shell environment, and you can alter/modify it. So the contents of the JAVA_HOME environment is altered in the child process, but the child process can't affect the environment of the parent process in your interactive shell.

You can setup the environment for your interactive shell in various places depending on the shell (~/.bash_profile is one for bash as you alluded to in your question).  See the linked answer in the comment to your question for the best way to 'permanently set' environment values.