Java Program to Reverse a String In-place

In this post we’ll see a Java program to reverse a String in-place. If we go by the definition of an in-place algorithm it doesn’t use any extra space the space of the input data itself is used to modify the data and produce the output.

Now we do know that String is immutable in Java so any modification to the original String results in creation of a new String object. That is in contrast to the in-place algorithm which requires that you shouldn’t use a new data structure to produce output. So, technically having an in-place algorithm for reversing a String in Java is not possible but stretching the technicality a bit we can argue that original string, if not used any more, gets garbage collected leaving us with single string object anyway. Keeping that argument in mind we can write a Java program to reverse a String in-place.

There are two options for writing this program if you are permitted to use other classes then you can use StringBuilder class and its methods. If you are not permitted to use any Java library the you can do it by iterating the String.

Reverse String using StringBuilder

One thing to note here is that you don’t need to iterate the whole String, you need to iterate only n/2 String for the String of size n. Since the first and last chars, second and second last and so on are swapped in each iteration so by the time middle char is reached the String is already reversed.

Following image shows the same-

reverse string in place java

public class ReverseString {
  public static void main(String[] args) {
    String str = "Hello World";
    reverseString(str);
  }

  static void reverseString(String str) {
    StringBuilder sb = new StringBuilder(str);
    int n = sb.length();
    char temp;
    for (int i = 0; i < n / 2; i++) { 
      temp = sb.charAt(i);
      sb.setCharAt(i, sb.charAt(n - i - 1));
      sb.setCharAt(n - i - 1, temp);
    } 
    System.out.println("Reversed String- " + sb.toString());
  }
}

Output

Reversed String- dlroW olleH

As you can see in this program StringBuilder class and it’s setCharAt() method is used to reverse String.

Reverse String using char Array

Every String is internally stored as a char array so we can get that array and reverse it, reversing the String in the process. This program is similar to reversing an array in-place in Java.

public class ReverseString {
  public static void main(String[] args) {
    String str = "Hello World";
    reverseString(str);
  }

  static void reverseString(String str) {
    char[] charArr = str.toCharArray();
    int n = charArr.length;
    char temp;
    for (int i = 0; i < n / 2; i++) { 
      temp = charArr[i]; 
      // Swapping
      charArr[i] = charArr[n - i - 1]; 
      charArr[n - i - 1] = temp; 
    } 
    String rstr = new String(charArr);
    System.out.println("Reversed String- " + rstr);
  }
}

Output

Reversed String- dlroW olleH

Though the whole process of reversing is done using the space of the input String (which is internally stored as char array) itself but a new String is created using the reversed char array. Taking our argument that original string will get garbage collected we can say that we are left with a single object.

Related Posts

That’s all for the topic Java Program to Reverse a String In-place. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.