Calculator which follows BODMAS rules in Java

Today we’ll implement a calculator that follows BODMAS rule in Java.

BODMAS expands to- Bracket Of Division Multiplication Addition Subtraction. It is a global norm for performing arithmetic calculations. Following this order, we achieve correct arithmetic results.

The example expressions undergoing BODMAS evaluation are in the code itself. The resultant output has the solved answers for these expressions.

Implementation of BODMAS in Java

Implementing this code requires importing java.util.Stack.

  • We’ll be pushing our elements into the stack,
  • Parsing the expression to identify the tokens
  • The token can be operand or operator
  • If brackets come, the highest priority is given to its enclosing expression
  • Rest of the stack contains the remaining tokens
  • Evaluation of remaining tokens takes place
  • We’ll be repeating this procedure until the result reaches the top of the stack.
import java.util.Stack; 
public class B_C 
 public static int solve_this(String expression) 
  char[] ar_tok = expression.toCharArray(); 
// This is the Stack for numbers, our values
 Stack<Integer> values = new Stack<Integer>(); 
// This Stack is for our Operators called 'sta_obj' 
Stack<Character> sta_obj = new Stack<Character>(); 
for (int i = 0; i < ar_tok.length; i++){
// Our present token is a whitespace? so skip it
if (ar_tok[i] == ' ') 
// Our token is a number? push it onto the stack for numbers 
if (ar_tok[i] >= '0' && ar_tok[i] <= '9') 
 StringBuffer buff_s = new StringBuffer(); 
// Incase the number has more than one digit
while (i < ar_tok.length && ar_tok[i] >= '0' && ar_tok[i] <= '9') 
// Our token is an opening bracket? push it onto 'sta_obj' 
else if (ar_tok[i] == '(') 
// Once we meet the closing bracket , solve the complete bracket 
else if (ar_tok[i] == ')') { 
while (sta_obj.peek() != '(') 
values.push(applyOp(sta_obj.pop(), values.pop(), values.pop())); 
// Incase the token is an operator 
else if (ar_tok[i] == '+' || ar_tok[i] == '-' || 
ar_tok[i] == '*' || ar_tok[i] == '/') 
// While top of 'sta_obj' has same or greater precedence to current 
// token, which is an operator. Apply operator on top of 'sta_obj' 
// to bring on top two elements in the values stack.
while (!sta_obj.empty() && hasPrecedence(ar_tok[i], sta_obj.peek())) 
values.push(applyOp(sta_obj.pop(), values.pop(), values.pop())); 
// Pushing the token onto 'sta_obj'. 
                sta_obj.push(ar_tok[i]); }} 
// Now that the expression is parsed, we'll use the rest of
/ sta_obj for the remaining values 
while (!sta_obj.empty()) 
values.push(applyOp(sta_obj.pop(), values.pop(), values.pop())); 
// If the top of 'values' has the result, simply return it 
        return values.pop();} 
// True is returned if 'oper_2' has higher or same precedence as 'oper_1', 
// else false is returned 
 public static boolean hasPrecedence(char oper_1, char oper_2){ 
 if (oper_2 == '(' || oper_2 == ')') 
  return false; 
 if ((oper_1 == '*' || oper_1 == '/') && (oper_2 == '+' || oper_2 == '-')) 
  return false; 
  return true;}
    // Here's a utility method for applying an operator 'oper' on the operands 'var1' and 'var2' 
    public static int applyOp(char oper, int var2, int var1) 
     switch (oper){ 
     case '+': 
        return var1 + var2; 
     case '-': 
        return var1 - var2; 
     case '*': 
        return var1 * var2; 
     case '/': 
         if (var2 == 0) 
         throw new
         ArithmeticException("division by zero.. immpossible!"); 
         return var1 / var2; 
 return 0;} 
// Main section 
public static void main(String[] args) 
System.out.println(BOD_Calc.solve_this("50 + 5 * (70/70)")); 
System.out.println(BOD_Calc.solve_this("50 + 5 * 70/70")); 
System.out.println(BOD_Calc.solve_this("100 + 5 * 30")); 
System.out.println(BOD_Calc.solve_this("100 * ( 5 + 30 ) "));
System.out.println(BOD_Calc.solve_this("100 / 0"));


In the above code, B_C is the main Class. It has the following methods:

  • int solve_it()
  • boolean hasPrecedence()
  • int calc_Op()
  • Main()

Likewise, int solve_it() basically brings everything to a character array, to parse the expression. Here ar_tok is the character array storing the parse tokens. For pushing numbers onto stack we have ‘val_sta’ , and for pushing operators onto stack we have ‘sta_obj’. After the declaration of variables, we move to the parsing of the expression. Parsing the expression requires StringBuffer class,  with its instance ‘buff_s’.

Moreover, to check the precedence of operators, boolean hasPrecedence() is given. Since it is boolean, returning true or false indicates the priority. Moving on to applyOp().

int calc_Op() is the actual calculator. A switch case of the operator determines the performing arithmetic operation. Special vigilance is by the exception block for division by zero, as in the code.

The main section comprises of the expressions yet to undergo evaluation.


The sample code snippet produces the following output:

Exception in thread "main" java.lang.ArithmeticException: division by zero.. immpossible!

Thus, the following code produces the following output. Prior knowledge of Java syntaxes, concepts, and methods would come in handy.

To learn more about stack operations, refer the following links:

How Java objects are stored in memory

Leave a Reply

Your email address will not be published. Required fields are marked *