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:

Spring WebFlux Filters
Guide to PriorityBlockingQueue in Java
Java Program to Implement Triply Linked List
Disable Spring Data Auto Configuration
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Java Program to Implement Bellman-Ford Algorithm
Getting Started with Stream Processing with Spring Cloud Data Flow
Java Program to Check Whether a Directed Graph Contains a Eulerian Path
Java Program to Perform Quick Sort on Large Number of Elements
Java Program to Find the Number of Ways to Write a Number as the Sum of Numbers Smaller than Itself
Java TreeMap vs HashMap
Java Program to subtract two large numbers using Linked Lists
Spring MVC + Thymeleaf 3.0: New Features
Java Program to Implement Bloom Filter
Quick Guide on Loading Initial Data with Spring Boot
A Guide to JUnit 5 Extensions
Spring Boot - Tracing Micro Service Logs
Prevent Cross-Site Scripting (XSS) in a Spring Application
Tạo ứng dụng Java RESTful Client với thư viện Retrofit
Java Program to Find Shortest Path Between All Vertices Using Floyd-Warshall’s Algorithm
Java Map With Case-Insensitive Keys
Adding Shutdown Hooks for JVM Applications
REST Pagination in Spring
Java Program to Generate All Possible Combinations Out of a, b, c, d, e
ETags for REST with Spring
Comparing Dates in Java
Java Program to Implement Ternary Search Tree
Tiêu chuẩn coding trong Java (Coding Standards)
Allow user:password in URL
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
Java Program to Implement Graph Coloring Algorithm
Java Program to Implement Solovay Strassen Primality Test Algorithm