IOP easiest is to use the javascript eval function
//The eval() function evaluates JavaScript code represented as a string.
console.log(eval('2 + 2'));
// expected output: 4
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
If you want to do this in java you can use the built in javascript engine see this answer on Stackoverflow:
https://stackoverflow.com/questions/3422673/how-to-evaluate-a-math-expression-given-in-string-form
Hope this helps,
Andrej