I have a form data which recieved java code from user and store it in the database.
So how do I sanitize the input to make sure that it is indeed java code?
what do you want to achiveve with that, you want to save java code to database?, well if you want to do something like that then you need regular expressions i think, thats the first thing it comes to my head
This sounds somewhat dangerous (not the storing of java text code in a DB), but why would such a use case come up. Nevertheless...
If you are not going to be expecting all aspects of the Java language, you may want to look into BeanShell. Beanshell can take java source code and evaluate it without compiling. You can likely "source" the code without executing it. If it passes, then it is java code, if not, then it is not java code. However, Beanshell does not accept all modern syntax and structures of newer Java editions.
One easy way to verify that it is indeed java code is to try to compile it (this of course gets messy if the code requires dependencies). If you do take this route, then make sure you are compiling in a DMZ computer/user (I am not aware of any risks of compiling untrusted code, but there might be).... just don't run the code after you compile it!