Reverse a String in Java – 4 Simple Methods
Reversing a string is a frequently asked interview question and a great exercise for beginners learning Java. Below are four common ways to reverse a string.
1. Using for
Loop
public class ReverseStringLoop {
public static void main(String[] args) {
String input = "SpringJavaLab";
String reversed = "";
for (int i = input.length() - 1; i >= 0; i--) {
reversed += input.charAt(i);
}
System.out.println("Reversed: " + reversed);
}
}
2. Using StringBuilder
public class ReverseStringBuilder {
public static void main(String[] args) {
String input = "SpringJavaLab";
StringBuilder sb = new StringBuilder(input);
System.out.println("Reversed: " + sb.reverse());
}
}
3. Using Recursion
public class ReverseStringRecursion {
public static String reverse(String str) {
if (str == null || str.length() <= 1) {
return str;
}
return reverse(str.substring(1)) + str.charAt(0);
}
public static void main(String[] args) {
String input = "SpringJavaLab";
System.out.println("Reversed: " + reverse(input));
}
}
4. Using Java 8 Streams
import java.util.stream.Collectors;
public class ReverseStringStream {
public static void main(String[] args) {
String input = "SpringJavaLab";
String reversed = new StringBuilder(input)
.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.collectingAndThen(
Collectors.toList(),
list -> {
java.util.Collections.reverse(list);
return list.stream()
.map(String::valueOf)
.collect(Collectors.joining());
}
));
System.out.println("Reversed: " + reversed);
}
}
💡 Conclusion
There are multiple ways to reverse a string in Java. Choose StringBuilder
for performance, recursion for learning, and streams for a functional approach. Practicing these helps improve logic and understanding of Java's core features.
You might also want to check for Palindrome Strings using the reversed string.
✨ Stay connected for more Java tutorials at Spring Java Lab.