How to Check Balancing of Symbol using Stack in Java

Connect with

Oracle JavaThis post is about checking a balancing of Symbol (parenthesis) in a mathematical expression using Stack in Java. Let us consider few expression whether its balance or not. In programming interview this can be asked to check whether you know the Stack basic or not.

1. Algorithm to Check parenthesis in Expression

I use following steps to check bracket symbol i.e. “( ) { } [ ]” in mathematical expression.

  1. create a Stack
  2. use loop to iterate one by one character in the expression.
    1. if character is not a symbol ignore it.
    2. if character is symbol i.e. opening symbol i.e. either ( or { or [ , push it into Stack.
    3. if character is closing symbol i.e. either ) or } ] , pop it from stack and match correspondingly. if matched then return true else false.

2. Java program to check balancing of bracket

This is a java program to check balancing of bracket/symbol in the expression.

package com.mysoftkey.ds.stack;

import java.util.Stack;

/**
 * Java program to check whether mathematical symbol/bracket is balanced
 * or not. 
 * 
 * @author ranjeet Jha
 *
 */
public class ParenthesisBalancingExample {

 public static void main(String[] args) {
  String exp1 = "[3+(4-9)]";
  System.out.println("Expression " + exp1 + " isBalance : " + isBalanceSymbolInExpression(exp1));
  String exp2 = "(3+45-({4[3-5+3/4]-9)}}]";
  System.out.println("Expression " + exp2 + " isBalance : " + isBalanceSymbolInExpression(exp2));
  String exp3 = "((a+b)+[c-d])";
  System.out.println("Expression " + exp3 + " isBalance : " + isBalanceSymbolInExpression(exp3));
}

/**
 * Java program to check symbol is balance in expression or not.
 * it means all the methematical parenthesis is balances in expression or not.
 * if yes then return true, else false
 * 
 * @param exprssion
 * @return
 */
public static boolean isBalanceSymbolInExpression(String exprssion) {
      Stack stk = new Stack();
      if(exprssion == null || exprssion.length() == 0) {
           return false;
      } else {    
        for(int i = 0; i < exprssion.length(); i++){
            
          if (exprssion.charAt(i) == '(' || exprssion.charAt(i) == '{' || exprssion.charAt(i) == '[' ) {
        		stk.push(exprssion.charAt(i));
          } else if(exprssion.charAt(i) == ')') {
	      if(!stk.isEmpty() && stk.peek() == '(') {
	            stk.pop();
	        }else {
	            return false;
	       }
          } else if (exprssion.charAt(i) == ']') {
               if(!stk.isEmpty() && stk.peek() == '[') {
                  stk.pop();
              } else {
                  return false;
              }
          } else if(exprssion.charAt(i) == '}'){
              if(!stk.isEmpty() && stk.peek() == '{') {
                  stk.pop();
              } else {
                  return false;
              }
          }
        }
        
        // if stack is empty finally , it means symbol is balance in expression
        if(stk.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
 }
}

3. Output to Check Parenthesis in Expression

This is output of above program to check symbol is balanced in the expression using Stack in Java.


Expression [3+(4-9)] isBalance : true
Expression (3+45-({4[3-5+3/4]-9)}}] isBalance : false
Expression ((a+b)+[c-d]) isBalance : true

Your comments/suggestions are welcome to improve this article. happy learning 🙂


Connect with

3 thoughts on “How to Check Balancing of Symbol using Stack in Java

  1. Pingback: Ashna
  2. Pingback: 2019

Leave a Reply

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