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 find the peak element of an array using Binary Search approach
A Guide to @RepeatedTest in Junit 5
@DynamicUpdate with Spring Data JPA
Java Program to Implement ArrayList API
Java Program to Check Cycle in a Graph using Topological Sort
Getting Started with GraphQL and Spring Boot
Thao tác với tập tin và thư mục trong Java
Custom Thread Pools In Java 8 Parallel Streams
Configuring a DataSource Programmatically in Spring Boot
Loại bỏ các phần tử trùng trong một ArrayList như thế nào trong Java 8?
Compact Strings in Java 9
Guide to UUID in Java
Mệnh đề Switch-case trong java
Java Program to Implement the Vigenere Cypher
SOAP Web service: Upload và Download file sử dụng MTOM trong JAX-WS
Java Program to Check whether Undirected Graph is Connected using DFS
Calling Stored Procedures from Spring Data JPA Repositories
Comparing Dates in Java
Spring Cloud Connectors and Heroku
Java Program to Implement Heap Sort Using Library Functions
How to use the Spring FactoryBean?
Reactive Flow with MongoDB, Kotlin, and Spring WebFlux
Tạo ứng dụng Java RESTful Client với thư viện OkHttp
Java Program to Implement Miller Rabin Primality Test Algorithm
Encode a String to UTF-8 in Java
Spring MVC Custom Validation
Java Program to Compute DFT Coefficients Directly
Java Program to Compute Discrete Fourier Transform Using Naive Approach
Ép kiểu trong Java (Type casting)
Java Program to Represent Graph Using Adjacency List
Java Program to Delete a Particular Node in a Tree Without Using Recursion
LinkedHashSet trong java