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:-

#HappyCoding

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.
%d bloggers like this: