Sudhakar Rayavaram
Problem solver (And maker),
Inquisitive (Root to most of my problems),
Software craftsman (Don't ask me for estimates)

Part of TarkaLabs

Technical Advisor for SportIndia

10 Nov 2010
eval() in Java?

Here is the question from my friend (ex-colleague):

“I have a mathematical expression say (45 %2B ((4 – 25) %2B 2)) as a string. How can you evaluate it to find the result using JAVA programming language?”

Well, this is very easy with javascript as it has the powerful eval() function. But java is static, strongly typed, not-that-flexible language. So, this cannot be provided as a language feature which leads me to either search for some available libraries or, write my won little library. If you are reading this post, you know by now what my decision was:) Come on, what’s fun in searching for someone’s work ;) (Well, not always)

So, here it is… This would have been much simpler with dynamic language like Groovy… But, the requirement clearly said JAVA

Logic is quite simple. The given input is an infix expression. Use stack and keep pushing all the elements (including braces) till you encounter a closed brace. Now, popping from the stack till you encounter an open brace will get you an operator and 2 operands. Evaluate it and push back the result to continue the same logic till the end of the input string.

 1   package com.rs.utils;
 2 
 3   import java.util.ArrayList;
 4   import java.util.Stack;
 5   import java.util.regex.Matcher;
 6   import java.util.regex.Pattern;
 7 
 8   public class Evaluator {
 9 
10      public static int eval(String infixExpression) {
11          Stack<String> stack = new Stack<String>();
12          String trimmedExp = infixExpression.replaceAll(" ", "");
13          for (String c : split(trimmedExp)) {
14              if (")".equals(c)) {
15                  if (!"(".equals(stack.peek())) {
16                      String result = performOperation(stack.pop(), stack.pop(),
17                              stack.pop()) + "";
18                      stack.pop(); // remove also the open bracket
19                      stack.push(result);
20                  }
21              } else {
22                  stack.push(c);
23              }
24          }
25          return Integer.parseInt(stack.pop());
26      }
27 
28      private static int performOperation(String operand2, String operator,
29              String operand1) {
30          int op1 = Integer.parseInt(operand1);
31          int op2 = Integer.parseInt(operand2);
32          switch (operator.toCharArray()[0]) {
33              case '+': return op1 + op2;
34              case '-': return op1 - op2;
35              case '*': return op1 * op2;
36              case '/': return op1 / op2;
37              default: return 0;
38          }
39      }
40 
41      static String[] split(String exp) {
42          ArrayList<String> parts = new ArrayList<String>();
43          Pattern pat = Pattern.compile("\\d++|\\+|\\-|\\*|/|\\(|\\)");
44          Matcher matcher = pat.matcher(exp);
45          while (matcher.find()) {
46              parts.add(matcher.group());
47          }
48          return parts.toArray(new String[0]);
49      }
50   }