Reverse string in Java

Vedant Kumar
4 min readAug 12, 2021

Hey There again. In today’s article, we will cover how to reverse strings in java and various ways of accomplishing it. Without any further delay, let’s leap into the introduction.

Introduction

We all know that string is an array or sequence of characters arranged in a specific order. In Java, a String is also considered / used as an object. In Java, we can leverage various operations that can be performed on a string object. Of them all, one that is most common and widely used is string reversal. By the end of this article, you will be accustomed to techniques of string reversal.

The article will cover the following techniques of string reversal:

  1. CharAt method
  2. Recursion
  3. String Buffer
  4. Iterative method

Let’s look at each of the above method one by one.

String reversal using CharAt appraoch

As the name suggests, CharAt() method will return characters at a specific location in a given string. A general approach to reverse a string by using CharAt() method is as follows:

  1. Take input string from the user or make consider some pre defined string on which the string reversal operation has to be performed.

2. Say, we have stored the input string in a variable named Target

3. Now, we can calculate the length of the input string by using the length() function. Assume this length value is stored in a variable length of type int.

4. The next step is to loop through each character in the input string in a reverse order, i.e., starting from the back. Using for loop we will loop length-1 times in a reverse manner and stack the characters we will achieve using Target.CharAt(i) (Assume i to be a variable that is decrementing from length-1 to 0).

5. The characters so stacked in the variable will be in reverse order and on printing it we will obtain the reversed version of the input string.

Code to implement string reversal using CharAt appraoch

import java.util.*;
public class StringReversal{
public static void main(String args[]) {
String Target, reverse=” ”;
Scanner input =new Scanner(System.in);
System.out.println(“Enter the string that you want to reverse”);
Target=input.nextLine();
int length=Target.length();
for(int i=length-1 ; i>=0 ; i — )
reverse=rev + Target.charAt(i);
System.out.println(“The reversed string so obtained is: “ rev);
}
}

String reversal using recursion

Recursion is a function that calls itself. In this technique, we will see how a function reverses the String by calling itself recursively.
So, to reverse a string we need to access each character separately. We already know that this can be done using the Char.At() method. Now, instead of looping, we will need a function and a condition till when the recursion can continue. The only possible conditions can be either the length of the string is 0 or some magnitude. Now, if the length is existent, we want to return the last element of the string. We do this by slicing the string, returning the end value, then slicing it further. The process is continued till the length becomes zero. And hen it does, we terminate the process. The slicing or subpart of the string is obtained by a substring() function that takes in two arguments. The first argument denotes the starting index and the second argument denotes the last index till which the string will be sliced.

Code to implement string reversal using recursion

import java.util.*;

public class StringReversal{

String reverse(String str)

{

if(str.length() == 0)

{

return “ “;

}

else

{

return str.charAt(str.length()-1) + rev(str.substring(0,str.length()-1)); }

}

public static void main(String[ ] args) {

StringReversal SR = new StringReversal();

Scanner input = new Scanner(System.in);

System.out.print(“Enter the string that has to be reversed : “);

String s=input.nextLine();

System.out.println(“The Reversed String so obtained is : “+ SR.reverse(s)); }

}

String reversal using String Buffer appraoch

Java StringBuilder is a class available in Java that is used to create mutable strings. It has various methods within the class that can be performed on strings. For example, append, insert, reverse, capacity, and many more. The reverse() function when called reverses the string.

Code to implement string reversal using String Buffer appraoch

import java.util.*;
public class StringReversal
{
public static String reverse(String SomeString){
return new StringBuilder(SomeString).reverse().toString();
}
public static void main(String[] args){
String s= “Welcome to this new article on string reversal in Java where we are reversing strings using StringBuilder;

// Note that strings are immutable in Java
s= reverse(s);
System.out.println(“Result after reversing a string is : “+s);
}
}

Similarly, one can also make use of a StringBuffer class reverse() method just like StringBuilder. The code remains the same as the previous one with just a minor change.

import java.util.*;
public class StringReversal
{
public static String reverse(String SomeString){
return new StringBuffer(SomeString).reverse().toString();
}
public static void main(String[] args){
String s= “Welcome to this new article on string reversal in Java where we are reversing strings using StringBuffer ;

s= reverse(s);
System.out.println(“Result after reversing a string is : “+s);
}
}

Both the classes yield the same results just that StringBuilder is preferred over the StringBuffer class as it is not synchronized. Just to make things clear, being synchronized means being thread safe. That is, it is not possible for two threads to call the methods of StringBuffer at the same time. StringBuilder is non-StringBuilder i.e. not thread safe.

String reversal using iterative method

This is an easy to understand and implement approach where we first convert a given string into an array of characters and then iterate in the reverse order character by character. toCharArray() method is used to convert a given string/strings into a character array.

Code to implement string reversal using iterative method

import java.util.*;
public class StringReversal{
// Creating a function to reverse a string in Java
public static String reverse(String s){
//Converting the string into a character array using toCharArray() method
char character[]=s.toCharArray();
String reversed=””;
//For loop to reverse a string
for(int i=character.length-1;i>=0;i — ){
reverse+=character[i];
}
return reverse;
}

public static void main(String[] args) {
System.out.println(reverse(“Welcome to the article”));
System.out.println(reverse(“Hope you enjoyed it”));
}
}

Conclusion

In this article, we have covered 4 ways of reversing strings in Java. I recommend practicing each of the aforementioned techniques and then decide a method that suits you. Hope you enjoyed it. Until next time.

--

--