Is there an eval() function in Java?

karthi_ms picture karthi_ms · Apr 9, 2010 · Viewed 171.2k times · Source

I have a string like the following:

String str = "4*5";

Now I have to get the result of 20 by using the string.

I know in some other languages the eval() function will do this. How can I do this in Java?

Answer

Jeff Storey picture Jeff Storey · Apr 9, 2010

You can use the ScriptEngine class and evaluate it as a Javascript string.

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval("4*5");

There may be a better way, but this one works.