Closure Compiler
You can use the Google Closure compiler.
It formats, compresses, optimizes and looks for errors in JavaScript code.
To quickly see what it can do, you can try the web service .
Example
For your example string
importClass(java.util.ArrayList); function fun(arg) { if (true){ return true;} else{ return true;}}
if you just want to format it, use the compilation options "Only spaces" and "Enough to type", which returns:
importClass(java.util.ArrayList); function fun(arg) { if(true) { return true }else { return true } } ;
In any case, with the Closure compiler, you have several options for optimizing and / or formatting the input code (specified as a string or file URI) and for returning an optimized / formatted JS as a string or saving it to a file.
I really recommend using the "simple" optimization mode. For longer Javascripts, this really saves a lot of unnecessary bytes. In addition, it speeds up script execution!
For your example line, compile the options "Simple" (instead of "Only spaces") and "Enough to type" return
importClass(java.util.ArrayList); function fun() { return!0 } ;
As you can see, the result of both fun() functions is the same (Boolean true ).
However, the second one has deleted all useless code (remaining valid!) And will be executed faster.
Download & Reference
Now the actual compiler is written in Java and is available as a command-line utility for downloading (Update 2014-07-10: New Downloadlink ).
As a second option, you can implement your own wrapper class to communicate with the REST API ( as I did for PHP ). It does not require too much effort / code.
Further information is available here:
Google Code Project Page
Beginning of work
Frequently Asked Questions: How do I call the Closure Compiler from the Java API? REST API Reference
Hope this helps.