Error messages are typically written to the standard error stream stderr instead of the standard output stream stdout. If java -version generates an error instead of what you expected (printing the version), it will likely do so to stderr. It is also possible that the version information could also printed to stderr.
The command substitution $() takes the output from stdout of what's inside the $() and substitutes it in its place. In case of an error, this could be nothing. If you are typing this from a terminal, you should still see any output (e.g. error messages) from java's stderr in the terminal.
java -versionshow when run from the command line? AddMSG=$(java -version 2>&1)and try again. It is probably outputting the information tostderrfor some reason. (some distros output that information tostdout, others tostderr.) For example opensuse 13.1 usesstdout, Archlinux usesstderr. (maybe newer versions usestderr)java not found.echo "$MSG"(i.e. quoted) for printing it & for using it otherwise.