How to reverse a string in java

Reversing a string means arranging the characters of a string in reverse order, that is, placing last character as first, second last character as second and so on.
Example of reversed string are string and gnirts, learning and gninrael etc.
This post will discuss different methods with program examples to reverse a string in java.

Method 1: Using StringBuffer
java.lang.StringBuffer class has a reverse method which reverses the string supplied to it. In order to create an object of this class, supply the string in its constructor. Example,

public class StringReverseDemo {
   public static void main(String[] args) {
	String str = "codippa";
        // create an object of stringbuffer
	StringBuffer buffer = new StringBuffer(str);
	System.out.println("Original string: " + str);
	System.out.println("Reversed string: " + buffer.reverse());
   }
}

Output of above program is

Original string: codippa
Reversed string: appidoc

You can also use java.lang.StringBuilder in place of java.lang.StringBuffer as it also has a reverse method.
Remember that a string cannot be reversed directly by using reverse function since there is no reverse function in string class.

Method 2: Using character array
If you are asked to reverse a string without using any string functions, then this is the method to learn. This method is based on the following algorithm

  1. Create a new character array of the same size as the number of characters in the string.
  2. Convert the source string into a character array.
  3. Iterate over the character backwards.
  4. In every iteration, add the current character to the new array created in Step 2. This character array will not hold the characters in reverse order.
  5. Create a new string with the array populated in Step 4.

Java program based on the above algorithm will be as below.

public class StringReverseDemo {
   public static void main(String[] args) {
	String str = "codippa";
	// create a new character array of string length
	char[] copyArray = new char[str.length()];
	// get characters of source string
	char[] stringChars = str.toCharArray();
	int startIndex = 0;
	// iterate over the string characters backwards
	for(int i = stringChars.length -1; i >=0; i--) {
	   // store characters in the copy array
	   copyArray[startIndex] = stringChars[i];
	   // increment the index of copy array
	   startIndex++;
	}
	// create a new string from character copy
	String reverse = new String(copyArray);
	System.out.println("Original string: " + str);
        System.out.println("Reversed string: " + reverse);
   }
}

Above code is written as per the algorithm stated earlier. In order to convert a character array to a string, use the constructor of java.lang.String class that takes a character array as argument.
In this method, you can also use a byte array instead of a character array. For converting a string to byte array, use string’s getBytes method. And for converting a byte array to a string, use string class constructor that takes a byte array as argument.

Method 3: Using character array and StringBuffer
This method is a combination of Method 1 and 2 above. In this method also, we convert the string to a character array and iterate over it in reverse order.
Instead of putting the character in a character array, it is added to a java.lang.StringBuffer object using its append method which is converted to a string using toString method.
Code follows.

public class StringReverseDemo {
   public static void main(String[] args) {
	String str = "codippa";
	// create a stringbuffer to hold the reversed string
	StringBuffer buffer = new StringBuffer();
	// get characters of source string
	char[] stringChars = str.toCharArray();
	// iterate over the string characters backwards
	for(int i = stringChars.length -1; i >=0; i--) {
	   // add character to stringbuffer
	   buffer.append(stringChars[i]);
	}
	// convert stringbuffer to string
	String reverse = buffer.toString();
	System.out.println("Original string: " + str);
        System.out.println("Reversed string: " + reverse);
   }
}

Output will be as below

Original string: codippa
Reversed string: appidoc

Method 4: Using arraylist
This method will follow the following steps.

  1. Convert the string to a character array.
  2. Initialize a java.util.ArrayList.
  3. Iterate over character array and in every iteration, add the current character to the array list created in Step 2.
  4. Reverse the elements of array list using reverse method of java.util.Collections class.
  5. Now iterate over the array list and print the current element in every iteration.

Code based on above steps is given below.

public class StringReverseDemo {
   public static void main(String[] args) {
	String s = "codippa";
	// get characters of source string
	char[] stringChars = s.toCharArray();
	// list to hold the characters
	List list = new ArrayList();
	// iterate over the string characters
	for(int i = 0; i < stringChars.length; i++) {
	   // add character to list
	   list.add(stringChars[i]);
	}
	// reverse the list elements
	Collections.reverse(list);
	for (int i = 0; i < list.size(); i++) {
	   System.out.print(list.get(i));
	}
   }
}

Instead of printing the reversed characters, if you want it as a string, then add the characters to a java.lang.StringBuffer or a character array as we did in the previous methods.
This method is not recommended to use and should only be used for learning purpose. It is highly inefficient since it involves iterating over the characters of the string twice. Thus, for larger string it will be very slow as compared to other methods.
Method 5: Swapping characters
This method reverses the string by swapping its characters from both ends. That is, exchanging the first character with the last, second with second last and so on.
For this, initialize two indexes: one at the leftmost position and other at the rightmost position. Now iterate till the start(or left) index is smaller that end(or right) index.
In each iteration, swap the characters. Thus, when the start index becomes equal to the end index, this means that all the characters are covered and the loop will terminate.
After the loop ends, the characters will be reversed.
Create a new string from this character array using the constructor of java.lang.String class.
Code is given below.

public class StringReverseDemo {
    public static void main(String[] args) {
	String str = "codippa";
	// get characters of source string
	char[] stringChars = str.toCharArray();
	// initialize start and end indexes
	int start = 0; 
	int end = stringChars.length - 1;
	// iterate over the character array
	while(start < end) {
	   // swap start and end characters
	   char temp = stringChars[end];
	   stringChars[end] = stringChars[start];
	   stringChars[start] = temp;
	   // increment start index
	   start++;
	   // reduce end index
 	   end--;
	}
	// create a new string with character array
	String reverse = new String(stringChars);
	System.out.println("Original string: " + str);
        System.out.println("Reversed string: " + reverse);
   }
}

Output of above program will be

Original string: codippa
Reversed string: appidoc

Method 6: Using recursion
A string can be reversed using recursion also. Though, it is not recommended to use recursion to reverse a string since it becomes an overhead when simpler methods are available but it forms a nice interview question.
For reversing a string by recursion, create a method that accepts a string and an index position. Call this method again and again with the index reduced every time by 1.
In every invocation of this method, it will extract the character at supplied index position and add it to the beginning followed by the string returned by calling this method with index reduced by 1.
When this method is called for the first time, the index is (length of string – 1). Thus, it will extract the last character and add it to the beginning.
When called second time, it will extract the second character and add it to the beginning. When the index becomes 0,  it will return the first character.
Thus, when the index becomes 0, the string returned will be the reverse of original string.
Code example follows.

public class StringReverseDemo {
    public static void main(String[] args) {
	String str = "codippa";
	// call recursive method with index of the last character
	String reverse = reverse(str, str.length() - 1);
	System.out.println("Original string: " + str);
        System.out.println("Reversed string: " + reverse);
   }
 
   /**
    * Recursive method to reverse a string
    * @param stringToReverse
    * @param position
    * @return
   */
   static String reverse(String stringToReverse, int position) {
	// index is zero, means return the first character
	if (position == 0) {
           return "" + stringToReverse.charAt(0);
	}
	// get character at supplied index
	char characterAtIndex = stringToReverse.charAt(position);
	// string with character at right end placed towards the left
	return characterAtIndex + reverse(stringToReverse, position - 1);
   }
}

Output is

Original string: codippa
Reversed string: appidoc

If you are asked to reverse a string in java using for loop, then go with Methods 2 and 5 since they do not involve any String class functions.
Hope you understood the method described in this post. If you found this post helpful, appreciate it by hitting the clap button below.

4

Leave a Reply

Mark Your Impression

  Subscribe  
Notify of
Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.