This post will discuss how to reverse a string using Stack in Java.

The following example demonstrates how to reverse a string with a Stack data structure in Java. Following are the complete steps:

  1. Create an empty stack of characters.
  2. Convert given string into character array using String.toCharArray() method and push each character of it into the stack.
  3. Remove characters from the stack until it becomes empty and assign them back to the character array. As stack follows FILO order, characters will be inserted in the reverse order.
  4. Finally, convert the character array into string using String.copyValueOf(char[]) and return the formed string.

The following program demonstrates it:

Download  Run Code

Output:

The reversed string is !em esreveR

 
We can also use StringBuilder instead of a character array, as shown below:

Download  Run Code

Output:

The reversed string is !em esreveR

That’s all about reversing a String using Stack in Java.