Make Selenium Easy

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

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

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.