FREQUENTLY ASKED JAVA PROGRAMS 35 – Java Program to Reverse a String Using Stack

Hello Folks,

As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a java program to reverse a string using stack.

Basics of Stack:-

Before we go for definition of Stack, let’s consider some examples:-

Suppose you have X number of plates. You organise them as one at the top of another. So the plate you kept first is in at the bottom and so on. Last plate will be on top. If you want a plate, obviously you should take plate which is in top ( Which was kept in last while organising ). We can summarize this as “Last In First Out (LIFO)”. The organised structure of plate is called a Stack.

Stack of plain white dinner plates, on white background

Stack is a data structure which works based on “Last In First Out (LIFO)” principal. There are mainly two points about stack:-

  1. New element will be added always on top.
  2. Element will be deleted only from top. You can not delete in between.

In Java, we have a Stack class which follows LIFO principal. It has two important method push() and pop().

push() – Pushes an item onto the top of this stack.

pop() – Removes the object at the top of this stack and returns that object as the value of this function.

Reverse a string using Stack:-

  1. Create an empty stack of Character.
  2. Convert given string to character array.
  3. Iterate char array from beginning and add to stack one by one.
  4. Now iterate stack till it is empty and create a string.
  5. You have reverse string now.

Java Program:-

package StringPrograms;

import java.util.Stack;

public class ReverseStringUsingStack {
	
	
	public static void main(String[] args) {
		
		
		// Given string to reverse 
		String stringToReverse = "MakeSeleniumEasy";
		
		// Convert string to char array
		char charArray[]= stringToReverse.toCharArray();
		
		// Creating an empty Stack 
		Stack charConatiner= new Stack<>();
		
		// Add characters of char array to Stack
		for(Character c: charArray)
		{
			charConatiner.push(c);
		}
		
		// Creating an empty string
		String reverseString ="";
		
		// Iterating Stack and creating string
		while(!charConatiner.isEmpty())
		{
			reverseString = reverseString + String.valueOf(charConatiner.pop());
		}
		
		System.out.println("Given String : "+reverseString);
		System.out.println("Reversed String : "+reverseString);
	}

}

#HappyCoding

Leave a Reply

Your email address will not be published. Required fields are marked *