You need to redirect to stdout before you can do this. These messages are sent to stderr by default, not to stdout; this means that grep will not see the messages and they will simply be printed to the console.
If it is Linux, try
java -version 2>&1 | grep whatever
and it should work. This will bring all the output to stderr from java execution and redirect it so that it moves to the same place as stdout; your grep call will be able to see it.
source share