Write a Java program to Checking Balanced Parentheses using a Stack
The code checks whether a string containing parentheses is balanced or not. Let's understand the code step by step:
- The code starts with the import statement import java.util.Stack; to import the Stack class from the java.util package.
- The BalancedParentheses class is defined, serving as the entry point of the program.
- In the main method, a string variable named input is declared and initialized with the value "(([{()}]))". This is the input string containing parentheses.
- A stack object named stack is created using generics, specifying that it will contain characters (Character).
- A boolean variable isBalanced is initialized to true. This variable will track whether the parentheses are balanced or not.
- A foreach loop is used to iterate over each character in the input string.
- Inside the loop, if the current character is an opening parenthesis ('(', '[', or '{'), it is pushed onto the stack using the push method.
- If the current character is a closing parenthesis (')', ']', or '}'), the code checks if the stack is empty. If it is empty, it means there is no corresponding opening parenthesis, and the parentheses are not balanced. In this case, the isBalanced variable is set to false, and the loop is terminated using the break statement.
- If the stack is not empty, the top character from the stack is popped using the pop method and stored in the top variable.
- The code then checks if the current character and the top character form a matching pair of parentheses. If they do not match, the isBalanced variable is set to false, and the loop is terminated using the break statement.
- After the loop, the System.out.println statement is used to print whether the parentheses are balanced or not by concatenating the string "Parentheses are Balanced ? " with the value of the isBalanced variable.
Source Code
import java.util.Stack;
public class BalancedParentheses
{
public static void main(String[] args)
{
String input = "(([{()}]))";
Stack<Character> stack = new Stack<>();
// Checking parentheses balance
boolean isBalanced = true;
for (char c : input.toCharArray())
{
if (c == '(' || c == '[' || c == '{')
{
stack.push(c);
}
else if (c == ')' || c == ']' || c == '}')
{
if (stack.isEmpty())
{
isBalanced = false;
break;
}
char top = stack.pop();
if ((c == ')' && top != '(') || (c == ']' && top != '[') || (c == '}' && top != '{'))
{
isBalanced = false;
break;
}
}
}
System.out.println("Parentheses are Balanced ? " + isBalanced);
}
}
Output
Parentheses are Balanced ? true