How to Check Balancing of Symbol using Stack in Java

Connect with

How to balanced parentheses using stack in javaBalance parentheses using stack in java. How to Check Balancing of Symbol (parentheses) in a mathematical expression using Stack in Java example.

1. Algorithm to Balanced parentheses using Stack in Java

This post is about checking the balancing of Symbols (parentheses ) in a mathematical expression using Stack in Java. Let us consider a few expressions whether it’s balanced or not. In a programming interview, this can be asked to check whether you know the Stack basic or not.

I use following steps to check bracket symbol i.e. "( ) { } [ ]" in mathematical expression. This algorith to check is very simple and you can write program very easily.

  1. create a Stack
  2. use loop to iterate one by one character in the expression.
  3. if character is not a symbol ignore it.
  4. if character is symbol i.e. opening symbol i.e. either ( or { or [ , push it into Stack.
  5. 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 (parentheses /brackets) 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 ParenthesesBalancingExample {

 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 mathematical parentheses is balanced in expression or not.
 * if yes then return true, else false
 * 
 * @param expression
 * @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 parentheses in Expression

This is output of above program balanced parentheses using stack in Java, or you can say, to check symbol whether its balanced in the expression or not 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

4. Reference

I hope you enjoyed this post of balanced parentheses using stack in Java, and you can visit data structure tutorial for more details.

Visit Wiki page.
Suggestions or comments are welcome to improve this post. cheers

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: Data Structure and Algorithm Tutorials | mySoftKey

  3. Pingback: 2019

Leave a Comment

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