Java Program to Reverse a String Using Stacks


In this article, we will understand how to reverse a string using stacks. String is a datatype that contains one or more characters and is enclosed in double quotes(“ ”). The stack is a linear data structure that is used to store the collection of objects. It is based on Last-In-First-Out (LIFO).

Below is a demonstration of the same −

Suppose our input is

Input string: Java Program

The desired output would be

Reversed string: margorP avaJ

Algorithm

Step 1 - START
Step 2 - Declare two string values namely input_string and result, a stack value namely stack, and a char value namely reverse.
Step 3 - Define the values.
Step 4 - Iterate over each characters of the string using a for-loop and push each character to the stack using ‘push’ keyword.
Step 5 - Now, pop each of the elements in the stack using ‘pop’ keyword and assign it to the result string.
Step 6 - Display the result
Step 7 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

import java.util.*;
public class ReverseString {
   public static void main(String[] args) {
      System.out.println("Required packages have been imported");
      String input_string = "Java Program";
      System.out.println("The string is defined as " +input_string);
      char[] reverse = new char[input_string.length()];
      Stack<Character> stack = new Stack<Character>();
      for (int i = 0; i < input_string.length(); i++) {
         stack.push(input_string.charAt(i));
      }
      int i = 0;
      while (!stack.isEmpty()) {
         reverse[i++] = stack.pop();
      }
      String result = new String(reverse);
      System.out.println("\nThe reversed string is: " + result);
   }
}

Output

Required packages have been imported
The string is defined as Java Program

The reversed string is: margorP avaJ

Example 2

Here, we encapsulate the operations into functions exhibiting object oriented programming.

import java.util.*;
public class ReverseString {
   public static String reverse_string(String input_string) {
      char[] reverse = new char[input_string.length()];
      Stack<Character> stack = new Stack<Character>();
      for (int i = 0; i < input_string.length(); i++) {
         stack.push(input_string.charAt(i));
      }
      int i = 0;
      while (!stack.isEmpty()) {
         reverse[i++] = stack.pop();
      }
      return new String(reverse);
   }
   public static void main(String[] args) {
      System.out.println("Required packages have been imported");
      String input_string = "Java Program";
      System.out.println("The string is defined as " +input_string);
      System.out.println("\nThe reversed string is: " + reverse_string(input_string));
   }
}

Output

Required packages have been imported
The string is defined as Java Program

The reversed string is: margorP avaJ

Updated on: 29-Mar-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements