java – How to calculate the value of an expression represented by a string and output it?


The thing is that I need to solve problems that have a String data type

For instance:

String bla = "5 + 10 - 5";

I need to get an answer like 10 . But, the option above will throw an error, since the characters + and - are not integers.

How can I solve this kind of problem, or are there other options, I will be grateful for practical advice?


Several solutions are possible:

  1. Write your own interpreter
  2. Connect a ready-made interpreter, for example exp4j
  3. Connect ScriptEngine like JavaScript (use case )
  4. Convert expression to java code (on the fly), compile and execute it
  5. Generate bytecode using bytecode generation library and execute it like Byte Buddy
Scroll to Top