Java Program to Reverse a String using Stack - The Coding Shala

Home >> Java Programs >> Reverse a String using Stack

 Hey there, welcome back to another post. In this post, we will learn how to reverse a string using a stack in Java.

Java Program to Reverse a String using Stack

As we know,  Stack data structure follows last in the first out (LIFO), so by using stack we can reverse a given string. For example: 

Input: hello
output: olleh

After storing into stack

  Stack ->  o

Now print stack -> olleh

Java Program: 

import java.util.Scanner;
import java.util.Stack;


public class Main {

    public static String doReverse(String str) {
        Stack<Character> stack = new Stack<>();

        // push all characters into stack
        for (int i = 0; i < str.length(); i++) {

        // pop characters from stack and build string
        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) {

        return sb.toString();

    public static void main(String[] args) {
        Scanner sc = new Scanner(;
        System.out.println("Enter a String");
        String str =;
        String reverse = doReverse(str);
        System.out.println("Reverse string is: " + reverse);


Enter a String
Reverse string is: alahsgnidoceht

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.


Popular Posts from this Blog

LeetCode - Crawler Log Folder Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

First Unique Character in a String Java - The Coding Shala

Add two numbers in Scala - The Coding Shala