Share on Google+Share on Google+

Reverse String using Stack

In this section, you will learn how to reverse the string using these operations.

Reverse String using Stack

You all are aware of Stack, a data structure, having two fundamental operations: push and pop. In stacks, items are removed in the reverse order from that in which they are added. The push operation is responsible for adding the element and pop for removing. Here we are going to reverse the string using these operations.

Here is the code:

import java.util.*;

class StackReverseString {
	public static String revString(String str) {
		Stack stack = new Stack();
		for (int i = 0; i < str.length(); i++) {
			stack.push(str.substring(i, i + 1));
		String strrev = "";
		while (!stack.isEmpty()) {
			strrev += stack.pop();
		return strrev;

	public static void main(String[] args) {
		Scanner scanner = new Scanner(;
		System.out.println("Enter a string: ");
		String str = scanner.nextLine();
		String reversedString = StackReverseString.revString(str);


Enter a String:
Hello World
dlroW olleH



Posted on: May 14, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null