How to Reverse Word in Java Program

How to Reverse Word in Java.


Let's see, how to Reverse Words in Java using Iteration and Recursion. We will Reverse a Word using Recursion and using loop. For reversing a word we should not use any inbuilt methods.

Input:      "ReverseWord"
Output:   "droWesreveR"

Input:      "HELLO"
Output:   "OLLEH"

Input:      "123abc"
Output:   "cba321"

Algorithm


1. Reverse a Word using Loop

STEP 1: Initialize i = word.length()-1 as we need to read the characters of Word from back.
STEP 2: Iterate till i>=0, that is to read all the characters of array till first character present at index 0.
STEP 3: Decrement i-- at each iteration as we are printing backwards.
STEP 4: Using word.charAt(i), method, pick each character of Word and Print it.
 
package javabypatel;

public class ReverseWordInJava {
 public static void main(String[] args) {  
  reverseWord("ReverseWord");
 }
 
 public static void reverseWord(String str){
  for (int i = str.length()-1; i >= 0; i--) {
   System.out.print(str.charAt(i));
  }
 }
}
 

2. Reverse a Word using Recursion

In this approach, we will Reverse a Word using recursion. 

In each Recursive step, we will pick character at index 0 and pass the remaining word to next Recursive call.
Repeat until word length is not equal to 0. When word length is == 0, Return word.


 
package javabypatel;

public class ReverseWordInJava {
 public static void main(String[] args) {  
  System.out.println(reverseWord("JavaByPatel"));
 }

 public static String reverseWord(String str) {     
  if (str.length() == 0) 
   return str;

  return reverseWord(str.substring(1)) + str.charAt(0);
 }
}
 

You may also like to see


Compress a given string in-place and with constant extra space.

Check whether a given string is an interleaving of String 1 and String 2.

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord.

Serialize and Deserialize a Binary Tree

Advanced Multithreading Interview Questions In Java

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Post a Comment