Reverse a String in java is a good coding related interview question. I have seen interviewee trying many ways to reverse a String using different ways. The idea of this post is to provide some of the popular ways to reverse a String and finally determine which is the best and correct way to reverse a string.
Table of Contents
Reverse a String in Java
Here are some of the popular ways that are found online to reverse a string in java program. Note that there is no reverse
method in String, otherwise we could have avoided all these workaround methods.
Reverse String using StringBuilder or StringBuffer
We know that StringBuffer and StringBuilder classes provide
reverse
method, so we can use that to reverse a string. Below is the code snippet showing how to use StringBuilder to reverse a string.String input = "java"; StringBuilder sb = new StringBuilder(input); String result = sb.reverse().toString(); System.out.println(result); //prints 'avaj'
Reverse String using Char Array
We can convert String to char array and then traverse it in reverse direction and populate a second char array from it. Then use the second char array to create the string that will be reversed of the first one. Below is the code for this approach.
String input = "java"; char [] ca = input.toCharArray(); char [] result = new char [ca.length]; int len = ca.length; for(char c : ca) { result[len-1] = c; len--; } System.out.println(new String(result));
Reverse String using Byte Array
Same approach as with char array, but using byte array. Code is shown below.
String input = "java"; byte [] ba = input.getBytes(); byte [] result = new byte [ba.length]; int len = ba.length; for(byte b : ba) { result[len-1] = b; len--; } System.out.println(new String(result));
Reverse String Word by Word
Sometimes we want words to be reversed in a sentence, not char by char. Below is a simple code showing how to do it using String split function and StringBuilder.
String inputLine = "God is Good";
String[] words = inputLine.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = words.length-1; i >= 0; i--) {
sb.append(words[i]).append(' ');
}
//trim to remove last white space
System.out.println("Reverse words = '" + sb.toString().trim()+"'");
Best way to reverse String in Java?
So from above three approaches, which is the correct and best one. As you can see above that all the three approaches works fine for the simple given input. If you read the String class javadoc, it has some interesting points.
The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).
So it seems that for some unicode characters, it will take two index positions in the char array or byte array. Will it have any effect on the code we have seen above to reverse the String. Let’s find out by writing a simple class where we will take user input using Scanner class and reverse it by using all the three methods above.
package com.journaldev.string;
import java.util.Scanner;
public class JavaReverseString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Input String:");
String input = sc.nextLine();
System.out.println("Enter Input Sentence:");
String inputLine = sc.nextLine();
sc.close();
reverseUsingStringBuilder(input);
reverseUsingByteArray(input);
reverseUsingCharArray(input);
reverseWords(inputLine);
}
private static void reverseUsingByteArray(String input) {
byte[] ba = input.getBytes();
byte[] result = new byte[ba.length];
int len = ba.length;
for (byte b : ba) {
result[len - 1] = b;
len--;
}
System.out.println("Reversed String using Byte Array = " + new String(result));
}
private static void reverseUsingCharArray(String input) {
char[] ca = input.toCharArray();
char[] result = new char[ca.length];
int len = ca.length;
for (char c : ca) {
result[len - 1] = c;
len--;
}
System.out.println("Reversed String using Char Array = " + new String(result));
}
private static void reverseUsingStringBuilder(String input) {
// use StringBuffer for Java < 1.5
StringBuilder sb = new StringBuilder(input);
System.out.println("Reversed String using StringBuilder = " + sb.reverse());
}
private static void reverseWords(String inputLine) {
String[] words = inputLine.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
sb.append(words[i]).append(' ');
}
// trim to remove last white space
System.out.println("Reverse words = '" + sb.toString().trim() + "'");
}
}
Below is a sample output for one of the test run.
Enter Input String:
JournalDev
Enter Input Sentence:
JournalDev is Good
Reversed String using StringBuilder = veDlanruoJ
Reversed String using Byte Array = veDlanruoJ
Reversed String using Char Array = veDlanruoJ
Reverse words = 'Good is JournalDev'
So it seems all the methods are working fine for normal english characters based String. Now below image shows another run where unicode characters are present in the input string.
So in above scenario, byte array reverse didn’t worked properly. However StringBuilder and char array approach worked fine. I haven’t tried with supplement characters as input string for above program, but if I look at the javadoc for StringBuilder reverse function API, it says:
So it seems supplement characters are being taken care of in StringBuilder reverse() method. That’s why if there is any need to reverse a string, my recommendation is to use StringBuilder reverse() method.
Well somehow I got to read lots of articles on your blog. It’s amazing how interesting it is for me to visit you very often.