Write a Java program to Reversing a String using a Stack


The code demonstrates how to reverse a string using a stack in Java. Let's go through 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 StringReverse class is defined, serving as the entry point of the program.
  • In the main method, a string variable named str is declared and initialized with the value "Tutor Joes". This is the original string that we want to reverse.
  • A stack object named stack is created using generics, specifying that it will contain characters (Character).
  • The System.out.println statement is used to print the original string by concatenating the string "Original String : " with the value of str.
  • A foreach loop is used to iterate over each character in the str string. Each character is pushed onto the stack using the push method.
  • A StringBuilder object named rev_str is created to store the reversed string.
  • A while loop is used to pop characters from the stack until it is empty. Each popped character is appended to the rev_str using the append method.
  • The System.out.println statement is used to print the reversed string by concatenating the string "Reversed String : " with the value of rev_str.

Source Code

import java.util.Stack;
public class StringReverse
{
	public static void main(String[] args)
	{
		String str = "Tutor Joes";
		Stack<Character> stack = new Stack<>();
 
		System.out.println("Original String : " + str);
		// Pushing characters onto the stack
		for (char c : str.toCharArray())
		{
			stack.push(c);
		}
 
		// Popping characters from the stack to reverse the string
		StringBuilder rev_str = new StringBuilder();
		while (!stack.isEmpty())
		{
			rev_str.append(stack.pop());
		}
 
		System.out.println("Reversed String : " + rev_str);
	}
}
 

Output

Original String : Tutor Joes
Reversed String : seoJ rotuT