It is recommended to check default terminal shell before set JAVA_HOME environment variable, via following commands:
$ echo $SHELL
/bin/bash
If your default terminal is /bin/bash (Bash), then you should use @Adrian Petrescu method.
If your default terminal is /bin/zsh (Z Shell), then you should set these environment variable in ~/.zshenv file with following contents:
export JAVA_HOME="$(/usr/libexec/java_home)"
Similarly, any other terminal type not mentioned above, you should set environment variable in its respective terminal env file.