How to reverse a String in Java
I guess that if you are on this page is because you are preparing for a Java interview.
Often this is a question asked during a job interview. In many years of Java development I don’t think I needed to reverse a String
very often. Anyway … the ‘official’ method is to use StringBuilder
, this comes with your Java Runtime and it's done in 1 line of code.
StringBuilder
The easiest method to reverse the string in Java is using StringBuilder
, the function is already present:
var stringToReverse = new StringBuilder("Java");
System.out.println(stringToReverse.reverse());
Output
"avaJ"
… but …
this question is smart but if you are really in an interview the other side want to see your logical skills. For this reason we show a more complicated solution :
private static String reverseString(String originalString){
// strings are immutable we extract the bytes
byte[] val = originalString.getBytes();
// we count how many bytes are in the string
int count = val.length;
// for each byte
int n = count - 1;
for (int j = (n-1) >> 1; j >= 0; j--) {
int k = n - j;
byte cj = val[j];
val[j] = val[k];
val[k] = cj;
// to better understand the algorithm we show the content 'of the result' at each iteration
// System.out.println(new String(val));
}
return new String(val);
}
This is a simplified version of the .reverse()
method of StringBuilder
. You can find the original on GitHub(AbstractStringBuilder
) If your interviewer doesn't like your answer ... well ... (s)he doesn’t like the Java official implementation.
To better understand how this algorithm works we introduce a super smelly System.out
just to show the ‘partial result’.
The call is the following: reverseString("I like Beans!”)
I likB eeans!
I lieB ekans!
I laeB ekins!
I naeB ekils!
IsnaeB ekil !
!snaeB ekil I
as you can see the method uses the >>
shift operator to find the center of the Array
and switch the position from the center to the sides using a temporary byte
to store the value to switch.
Maybe this is not THE easiest solution to present during an interview ... but not many interviewers can complain about your solution based on the Java source code ;-)
… for fun (or necessity) ...
if you want to show your knowledge to the interviewer you can tell him/her that in Java Strings are immutable and cannot be reversed without creating a new Object
... but you will show how to reverse the content of the original String
.
From the JavaDoc:
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings.
This answer can be used if you don’t remember how to reverse the String ... hoping that the interviewer enjoys your sense of humor and goes directly to the next question.