Pages

Thursday, September 5, 2024

Java Program To Reverse A String Without Using String Inbuilt Function reverse()

1. Introduction


In this tutorial, You'll learn how to write a java program to reverse a string without using string inbuilt function reverse().
This is a very common interview question that can be asked in many forms as below.

A) java program to reverse a string without using string inbuilt function
B) java program to reverse a string using recursion
C) java program to reverse a string without using the reverse method
C) Try using other classes of Java API (Except String).



The interviewer's main intention is not to use the String class reverse() method.


2. Solution 1: Using charAt() Method


String class charAt() method which takes the index and returns the character at the given position.

package com.java.w3schools.string.reverse;

public class ReverseString {

 public static void main(String[] args) {

  String str = "Hello world";
  String revString = "";

  for (int i = str.length() - 1; i >= 0; --i) {
   revString += str.charAt(i);
  }

  System.out.println(revString);
 }
}

Output:

dlrow olleH

In the above program, We are running a for loop from index 0 to its length. charAt(index) is invoked for each index and adding it to the new string revString.  All characters returned by charAt() method will be added to the revString string. After completing the for loop, the revString string will be having the reversed string. Let us take a look at the above output.


3. Solution 2: String Reversal Using Recursion Concept


Now we will write a java program for string reversal using recursion idea. Ideally, this is a very optimal and good solution. Here we will be calling a method printReverse() from the same method based on a condition. This condition is controlled by if condition.


This is to avoid the for loop and use the core programming efficient concept. If you do not write a good condition in if to stop the recursive call, then it will be calling continuously printReverse method. This is the drawback of recursive. If you are confident then you can apply recursion logic on any program.

package com.java.w3schools.blog.string;

/**
 * String reversal using recusion concept.
 * 
 * @author Java-W3schools Blog
 *
 */
public class StringReverseRecusive {

 public static void main(String[] args) {
  String input = "java-w3wschools blog";

  printReverse(input, input.length()-1);
 }

 private static void printReverse(String s, int pos) {
  if (pos > -1) {
   System.out.print(s.charAt(pos));
   printReverse(s, pos - 1);
  }
 }

}

Output:


golb sloohcsw3w-avaj


4. Solution 3: Using StringBuilder class


This is a third approach to solve this problem but just another way not to use the String reverse method. Some of the interviewers may not accept this solution. StringBuilder class is a mutable and final class. This provides a method to reverse its content.

package com.java.w3schools.blog.stringbuilder;

public class StringReverse {

 public static void main(String[] args) {
  String str = "Main String to be reversed";
  StringBuilder sb = new StringBuilder(str);
  str = sb.reverse().toString();
  System.out.println("Reversed String : " + str);

 }

}

Output:


Reversed String : desrever eb ot gnirtS niaM


5. Additional References:

Other references used in this article are below.

Enhanced For Loop Examples

StringBuilder API

Recursion wiki

6. Conclusion


We've seen the 3 possible solutions to reverse a string in java without using the reverse method.

Good way is to write a program to reverse a string using a recursive approach. This is to avoid the string reverse() method and for loop. Because for loop tells that you are using the very basic concepts of programming language. Better to use a recursive approach and explain properly to them.

If you like, please share it with friends.

No comments:

Post a Comment

Please do not add any spam links in the comments section.