This code snippets shows how to reverse a string using a stack.

package codesnippets;

import java.util.Scanner;
import java.util.Stack;
 * This code snippet shows a how to reverse a string using a Stack. 
public class StringReverse {
	public static void main(String [] args){
		Scanner scanner = new Scanner(;
		String str = "";
		Stack<String> stack = new Stack<String>();
		System.out.println("Enter a string to be reversed: ");
		str = scanner.nextLine();
		if (str == null || str.equals("")){
			System.out.println("It seems you aren't ready as yet to enter the string, ok buhbye !!");
		for (int i=0;i<str.length();i++){
			// Here we push all the characters in the string one by one into the Stack
		String strrev = "";
			// Here we pop all the elements from the Stack one by one which is essentially reversing.
			strrev += stack.pop(); 
		System.out.println("Reverse of the string \"" + str + "\" is: \"" + strrev + "\"");
About the Author

I enjoy the company of friends and family, though you would not find me in a big group of friends there would always be a number of friends whose friendship I cherish. I like to take care of the details while doing everything, this includes things I do at my job, home everywhere. Frankly speaking this habit can really be painful sometimes.