Stack Example

Stack Example 1: Reverse a string or word

In our previous article Stack Introduction and Implementation we had learnt how to implement stack in java. In this first example we will see how to reverse a word or a string using a stack.

When you run the following code, it will ask you to type a string. Once you type the string, press Enter, then it will print the string with letters in reverse order.

Stack Example 1: Reverse a string

package com.sneppets.dsalgo;


class MyStackImpl
	//max stack array size
	private int maxStackArraySize;
	//stack array
	private char[] myStackArray;
	//stack top
	private int top;
	public MyStackImpl(int size)
		//set stack array size
		maxStackArraySize = size;
		//create array
		myStackArray = new char[maxStackArraySize];
		//no elements in the stack array yet
		top = -1;
	public void push(char element)
		//increment top and insert the element in top of the stack array
		myStackArray[++top] = element;
	public char pop()
		//access the element from the top of the stack array
		return myStackArray[top--];
	public char peek()
		//peek at the top of the stack array
		return myStackArray[top];
	public boolean isEmpty()
		//return true is stack array is empty
		return (top == -1);
	public boolean isFull()
		//return true if stack array is full
		return (top == maxStackArraySize-1);

 * @author
class StackReverseString
	private String inputStr;
	private String outputStr;
	public StackReverseString(String inStr)
		inputStr = inStr;
	public String reverseInputString()
		int maxStackSize = inputStr.length();
		MyStackImpl myStack = new MyStackImpl(maxStackSize);
		for (int i=0; i<inputStr.length(); i++)
			char ch = inputStr.charAt(i);
		outputStr = "";
		while( !myStack.isEmpty())
			char ch = (char) myStack.pop();
			outputStr = outputStr + ch;
		return outputStr;

public class StackReverseStringExample {
	public static void main (String[] args) throws IOException
		String inStr, outStr;
			System.out.println("Enter a String to reverse: ");
			inStr = getInputString();
			StackReverseString stackReverseWord = new StackReverseString(inStr);
			outStr = stackReverseWord.reverseInputString();
			System.out.println("Reversed output string: " + outStr);

	public static String getInputString() throws IOException {
		InputStreamReader isr = new InputStreamReader(;
		BufferedReader br = new BufferedReader(isr);
		String inStr = br.readLine();
		return inStr;



Enter a String to reverse: 
Reversed output string: olleH


A stack is used to reverse the letters in a string.  Because stack follows Last In First Out (LIFO) principle, the stack reverses the order of characters.

Recommended Posts


Notify of

Inline Feedbacks
View all comments