It can be very dangerous to compile random code written by the user. But you can try using the Java Compiler API, or if you want something similar but not strictly java use groovy then (it is easier to to watch you want with the GroovyShell object)
I haven't tried to do something like this myself, but i found some useful answers here: Convert String to Code
Be very careful if you succeed.