Reverse the given String using Stack

Objective: Given a String, write a java program to reverse the string using Stack


Input: “tutorial horizon”
Output: “noziroh lairotut”

Recommended: Please read Stack Data Structure before continue to read.


  • Initialize a StringBuffer, this will be our output.
  • Initialize a Stack.
  • Traverse through string, one character at a time and keep adding it to Stack.
  • While stack is not empty, keep popping out the characters from stack and add it to the output StringBuffer.
  • Print the output.

Java Code:

import java.util.Stack;
public class ReverseStringStack {
static void reverse(String input){
StringBuffer output = new StringBuffer();
if(input==null || input.isEmpty())
Stack<Character> stack = new Stack<>();
for (int i = 0; i <input.length() ; i++) {
//traverse through stack, pop the characters and add it to StringBUffer
while (stack.empty()==false){
System.out.println("Original String: " + input);
System.out.println("Reverse String: " + output);
public static void main(String[] args) {
String input = "tutorial horizon";


Original String: tutorial horizon
Reverse String: noziroh lairotut