You can use the JEP Java expression parser libary (or another expression parser).
For example:
String foo = "a+b";
Jep jep = new Jep();
try {
jep.addVariable("a", a);
jep.addVariable("b", b);
jep.parse(foo);
Object result = jep.evaluate();
System.out.println("foo = " + result);
} catch (JepException e) {
System.out.println("An error occurred: " + e.getMessage());
}
EDIT:
It turns out that JEP (here: http://www.singularsys.com/jep/) is licensed software so you will have to pay, but there is another option.
There are many other similar libraries including JEPLite (http://jeplite.sourceforge.net/index.html) which seems (as far as I can tell) to be a free version and should be compatible.