Reverse a string in Java is a quite easy task.
I’ll provide you 6 pieces of Java code to reverse a string.
I think StringBuilder.reverse()
and StringBuffer.reverse()
are the best string reverse functions in Java.
It’s already optimized, looks simple and easy.
But sometimes you have a task to implement string reversal using for loop, recursion or even reverse a string word by word.
Java Reverse String Methods Overview
So you have a task: you need to write a Java program to reverse a string.
To be more precise – you need to write a code to reverse letters in a string.
I mentioned above about StringBuilder.reverse()
and StringBuffer.reverse()
.
First of all, the difference is StringBuffer is threadsafe and StringBuilder is not.
If you take one of these reverse methods it would be a good choice.
It’s a source code of String Builder reverse method:
public AbstractStringBuilder reverse() {
boolean hasSurrogates = false;
int n = count - 1;
for (int j = (n-1) >> 1; j >= 0; j--) {
int k = n - j;
char cj = value[j];
char ck = value[k];
value[j] = ck;
value[k] = cj;
if (Character.isSurrogate(cj) ||
Character.isSurrogate(ck)) {
hasSurrogates = true;
}
}
if (hasSurrogates) {
reverseAllValidSurrogatePairs();
}
return this;
}
Looks a little bit complicated, but you shouldn’t care about it, it’s a problem of JDK developers.
The most important for you is that this method is well-optimized and tested.
I prepared code examples in the next sections. Let’s take a look.
String Builder Reverse
Easy, fast and well-tested way to reverse a string, but not threadsafe.
Example:
public static void main(String[] args) {
String reversed = new StringBuilder("Hello String Builder!").reverse().toString();
System.out.println(reversed);
}
Output:
!redliuB gnirtS olleH
String Buffer Reverse
Easy, well-tested, threadsafe, but slower than StringBuilder.reverse().
Example:
public static void main(String[] args) {
String reversed = new StringBuffer("Hello String Buffer!").reverse().toString();
System.out.println(reversed);
}
Output:
!reffuB gnirtS olleH
String Utils Reverse
Apache Commons StringUtils is the most popular library to process strings.
It provides fancier API but uses StringBuilder.reverse()
method inside.
To include this library you should add maven dependency to your pom.xml:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>
and use StringUtils reverse method.
Example:
package com.explainjava;
import org.apache.commons.lang3.StringUtils;
public class ReverseStringExamples {
public static void main(String[] args) {
String reversed = StringUtils.reverse("Hello String Utils!");
System.out.println(reversed);
}
}
Output:
!slitU gnirtS olleH
Looks better but in general the same as a StringBuilder.
Reverse a String in a For Loop
The solution is simple:
- Get a char array from the source string.
- Create a target array to store chars.
- Iterate through source char array and store letters in target array in reverse order.
- Create a new string from the target array.
Example:
public static void main(String[] args) {
char[] letters = "Hello Reverse In For Loop!".toCharArray();
char[] reversedArray = new char[letters.length];
for (int i = 0; i < letters.length; i++) {
reversedArray[reversedArray.length - i - 1] = letters[i];
}
String reversed = String.valueOf(reversedArray);
System.out.println(reversed);
}
Or you can switch reversed array of chars to StringBuilder.
Example:
public static void main(String[] args) {
char[] letters = "Hello Reverse In For Loop!".toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = letters.length - 1; i >= 0; i--) {
sb.append(letters[i]);
}
String reversed = sb.toString();
System.out.println(reversed);
}
Or even without retrieving char array.
Example:
public static void main(String[] args) {
String source = "Hello Reverse In For Loop!";
StringBuilder sb = new StringBuilder();
for (int i = source.length() - 1; i >= 0; i--) {
sb.append(source.charAt(i));
}
String reversed = sb.toString();
System.out.println(reversed);
}
Output:
!pooL roF nI esreveR olleH
Reverse a String Using Recursion
The reverse function looks easy:
public static String reverse(String str) {
if (str == null || str.length() <= 1) {
return str;
}
return reverse(str.substring(1)) + str.charAt(0);
}
For example, you want to reverse “Hello” string.
The method will be executed 6 times:
reverse("Hello")
(reverse("ello")) + "H"
((reverse("llo")) + "e") + "H"
(((reverse("lo")) + "l") + "e") + "H"
((((reverse("o")) + "l") + "l") + "e") + "H"
(((("o") + "l") + "l") + "e") + "H"
Output:
olleH
Reverse Word Letters in a String
The task is to keep words in its places but reverse characters in each word.
The plan is the following:
- Split source string by whitespace to an array
- Reverse each string in an array
- Join an array of strings back to one string
The example is in Java 8:
public static void main(String[] args) {
String source = "Reverse String Word By Word";
String result =
Stream.of(source.split(" "))
.map(s -> new StringBuilder(s).reverse().toString())
.collect(Collectors.joining(" "));
System.out.println(result);
}
Output:
esreveR gnirtS droW yB droW
Reverse Words in String
The task is to reverse words in a string but letters in each word should not be changed.
Steps:
- Split by whitespace to list
- Reverse list
- Join back to string
The source code is in Java 8, but if someone needs I can provide an example without streams.
Example:
public static void main(String[] args) {
String source = "Reverse Words in String";
List<String> list = Arrays.asList(source.split(" "));
Collections.reverse(list);
String result = list.stream().collect(Collectors.joining(" "));
System.out.println(result);
}
The same behavior has StringUtils.reverseDelimited(s, c)
method.
Example:
public static void main(String[] args) {
String source = "Reverse Words in String";
String result = StringUtils.reverseDelimited(source, ' ');
System.out.println(result);
}
Output:
String in Words Reverse
Feel free to ask any questions.