Java Program to Check for balanced parenthesis by using Stacks

This is a Java Program to Check for balanced parenthesis by using Stacks. Parenthesis matching is commonly used for evaluating arithmetic expressions and in editors for validating syntax.

Here is the source code of the Java Program to check for balanced parenthesis by using stacks. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

/*
 *  Java Program to Check for balanced paranthesis by using Stacks
 */
 
import java.util.*;
 
public class ParenthesisMatching
{
    public static void main(String[] args) 
    {
        Scanner scan = new Scanner(System.in);
        /* Creating Stack */
        Stack<Integer> stk = new Stack<Integer>();
        System.out.println("Parenthesis Matching Test\n");
        /* Accepting expression */
        System.out.println("Enter expression");
        String exp = scan.next();        
        int len = exp.length();
        System.out.println("\nMatches and Mismatches:\n");
        for (int i = 0; i < len; i++)
        {    
            char ch = exp.charAt(i);
            if (ch == '(')
                stk.push(i);
            else if (ch == ')')
            {
                try
                {
                    int p = stk.pop() + 1;
                    System.out.println("')' at index "+(i+1)+" matched with ')' at index "+p);
                }
                catch(Exception e)
                {
                    System.out.println("')' at index "+(i+1)+" is unmatched");
                }
            }            
        }
        while (!stk.isEmpty() )
            System.out.println("'(' at index "+(stk.pop() +1)+" is unmatched");
    }
}
Parenthesis Matching Test
 
Enter expression
(a+(b*c)-d)
 
Matches and Mismatches:
 
')' at index 8 matched with ')' at index 4
')' at index 11 matched with ')' at index 1
 
 
 
Parenthesis Matching Test
 
Enter expression
((x+y/(z-w))
 
Matches and Mismatches:
 
')' at index 11 matched with ')' at index 7
')' at index 12 matched with ')' at index 2
'(' at index 1 is unmatched
 
 
 
Parenthesis Matching Test
 
Enter expression
(a+b*(c-d)-(e-f/(g+h*(k-i)/(l-j+k
 
Matches and Mismatches:
 
')' at index 10 matched with ')' at index 6
')' at index 26 matched with ')' at index 22
'(' at index 28 is unmatched
'(' at index 17 is unmatched
'(' at index 12 is unmatched
'(' at index 1 is unmatched

Related posts:

Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree
Java Program to Implement Sieve Of Sundaram
Java Program to Implement String Matching Using Vectors
Practical Java Examples of the Big O Notation
A Guide to Spring Cloud Netflix – Hystrix
Guide to java.util.concurrent.BlockingQueue
Java Program to Check if a Given Set of Three Points Lie on a Single Line or Not
Quản lý bộ nhớ trong Java với Heap Space vs Stack
Java Program to Find Second Smallest of n Elements with Given Complexity Constraint
Java Program to Perform Searching Using Self-Organizing Lists
Apache Commons Collections Bag
A Guide to System.exit()
Spring Security OAuth2 – Simple Token Revocation
Xây dựng ứng dụng Client-Server với Socket trong Java
Spring Autowiring of Generic Types
Một số tính năng mới về xử lý ngoại lệ trong Java 7
Overview of the java.util.concurrent
Java Program to do a Breadth First Search/Traversal on a graph non-recursively
Spring Boot - Batch Service
Hướng dẫn Java Design Pattern – DAO
String Processing with Apache Commons Lang 3
Java Program to Implement the MD5 Algorithm
Vòng lặp for, while, do-while trong Java
Java Web Services – JAX-WS – SOAP
HTTP Authentification and CGI/Servlet
SOAP Web service: Upload và Download file sử dụng MTOM trong JAX-WS
Unsatisfied Dependency in Spring
Hướng dẫn Java Design Pattern – Bridge
Performance Difference Between save() and saveAll() in Spring Data
Java Program to Implement the Edmond’s Algorithm for Maximum Cardinality Matching
Convert XML to JSON Using Jackson
A Guide to Queries in Spring Data MongoDB