Java Program to Check for Balanced Parenthesis by Using Stacks

You are currently viewing Java Program to Check for Balanced Parenthesis by Using Stacks

Are you looking to know about the “Java Program to Check for Balanced Parenthesis by Using Stacks”? If yes then refer to this article. Shall we start the article? Let’s go.

Java Program to Check for Balanced Parenthesis by Using Stacks

main.java

/*
 *  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");
    }
}

Final Words

I hope this article helps you to learn the “Java Program to Check for Balanced Parenthesis by Using Stacks”. If you face any issues please let me know via the comment section. Share this article with other Java program developers via social networks. Thank You!

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply