The only way to compile a java code is "javac" tool. And the syntax of this tool is that it always expects java code as a file.
You can use built-in exec() method in your java program to compile other java programs dynamically. In this exec() method you have invoke the "javac" command. But how will you ensure if your java code has no syntax errors. This may be little bit tough. But you can still know that.
Once you know class file is generated then you can load it dynamically using URLClassLoader class.
You can write java code in strings. But ultimately you may atleast need to create a temp file in your program where you copy the string and then do the compilation.
If compilation is successful then you can delete the temp files.