String reversal is a common task in programming that involves changing the order of characters in a string, so that the last character appears first and the first character appears last. Java provides a variety of methods to reverse a string, from simple loops to advanced collection manipulation using Java 8 Streams.
In this article, we’ll explore different methods to reverse a string in Java, including using loops, StringBuffer, StringBuilder, recursion, collections, and streams. Each method includes simple examples for easy understanding.
There are different ways to achieve reversal.
We will see them one by one.
- Using Loops (or Iterations)
- Reversing a String Using Loops
- Reversing a String Using StringBuffer or StringBuilder
- Reversing a String Using
toCharArray() - Reversing a String Using Recursion
- Reversing a String Using Collections
- Reversing a String Using Java 8 Streams
Let’s get started with the different methods to reverse strings in Java.
1 Reverse a string Using Loops
Following programs will show how to use loops to reverse a string.
Using loop we extracted one one character from string using charAt() of string to extract a character and assigned to another String or StringBuffer or in StringBuilder.
This program is also helpful in String reverse in java without using inbuilt function and in reverse a string without using string function in java
Below are the simple java programs for beginners
A. Reverse a string in java using for loop
- Create a String object
String string = "Programmer"; - Create a for loop to iterate it from string object length to 0
for (int i = string.length() - 1; i>= 0; i--) - Extract each character by using
charAt()and assign it to another String object.
public class StringReverse1 {
public static void main(String[] args) {
String string = "Programmer";
String reversedString = "";
for (int i = string.length() - 1; i >= 0; i--) {
reversedString+=string.charAt(i);
}
System.out.println("Reversed String is " + reversedString);
}
}
We run here java reverse for loop to get each characters and assigned to another string.
Printed the reversed String to get reverse string in java program.
B. Reverse a string in java using while loop
String object is inmutable so changing object value is not possible to avoid this we used StringBuffer here
public class StringReverse2 {
public static void main(String[] args) {
String string = "Programmer";
StringBuffer reversedString = new StringBuffer();
int i = string.length()-1;
while (i >= 0) {
reversedString.append(string.charAt(i));
i--;
}
System.out.println("Reversed String is " + reversedString);
}
}
C. Reverse a string in java using do while loop
Here StringBuilder is used to reverse the string
public class StringReverse3 {
public static void main(String[] args) {
String string = "Programmer";
StringBuilder reversedString = new StringBuilder();
int i = string.length() - 1;
do {
reversedString.append(string.charAt(i));
i--;
} while (i >= 0);
System.out.println("Reversed String is " + reversedString);
}
}
2. Using StringBuffer or StringBuilder classes
StringBuffer and StringBuilder provides a method reverse() to reverse the string.
This is very simple approach any one can easily reverse string using this approach.
Using this method we can reverse string.
import java.util.Scanner;
public class StringReverse4 {
public static void main(String[] args) {
System.out.println("Enter A string to reverse it");
Scanner scanner = new Scanner(System.in);
String string = scanner.next();
String reverseString = new StringBuffer(string).reverse().toString();
System.out.println("Reversed String is " + reverseString);
}
}
3. Using toCharArray() of Array
toCharArray() is used to convert String Object to character array.
We follow below steps to revers string using toCharArray().
- Take a String
- Conver it to Character array string.toCharArray();
- Reverse loop in character array
- Assing it to a string object
import java.util.Scanner;
public class StringReverse5 {
public static void main(String[] args) {
System.out.println("Enter A string to reverse it");
Scanner scanner = new Scanner(System.in);
String string = scanner.next();
char[] characters = string.toCharArray();
String reverseString = "";
for (int i = characters.length - 1; i >= 0; i--) {
reverseString += characters[i];
}
System.out.println("Reversed String is " + reverseString);
}
}
4. Using Recursion to reverse a String
Recursion is one of the common way to reverse a string.
In many java interviews, it also asked to reverse a string without using iteration and reverse a string in java without using inbuilt function . In that case we use recursion.
- Create a method to call itself
reverseString(String s) - If String is empty then return
- If not empty make recursion call to reverse a string
reverseString(s.substring(1)) + s.charAt(0);
import java.util.Scanner;
public class StringReverse6 {
public static String reverseString(String s) {
if (s.isEmpty()) {
return s;
} else {
return reverseString(s.substring(1)) + s.charAt(0);
}
}
public static void main(String[] args) {
System.out.println("Enter A string to reverse it");
Scanner scanner = new Scanner(System.in);
String string = scanner.next();
char[] characters = string.toCharArray();
String reversedString = reverseString(string);
System.out.println("Reversed String is " + reversedString);
}
}
5. Using Collections to Reverse a String in Java
- Get String
- Conver to List
List charList = string.chars()
.mapToObj(e -> (char) e)
.collect(Collectors.toList());
- Reverse List
Collections.reverse(charList); - Convert to String
String reverseString = charList.stream().map(String::valueOf).collect(Collectors.joining());
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class StringReverse7 {
public static void main(String[] args) {
System.out.println("Enter A string to reverse it");
Scanner scanner = new Scanner(System.in);
String string = scanner.next();
char[] characters = string.toCharArray();
List charList = string.chars()
.mapToObj(e -> (char) e)
.collect(Collectors.toList());
Collections.reverse(charList);
String reverseString = charList.stream().map(String::valueOf).collect(Collectors.joining());
System.out.println("Reversed String is " + reverseString);
}
}
Above program is a good example of Java 8 using Streams
Reversing a String Using Collections
Using Java’s Collections class, you can reverse a string by converting it to a List and applying the reverse() method on it.
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class StringReverse7 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string to reverse:");
String string = scanner.next();
List<Character> charList = string.chars()
.mapToObj(e -> (char) e)
.collect(Collectors.toList());
Collections.reverse(charList);
String reversedString = charList.stream()
.map(String::valueOf)
.collect(Collectors.joining());
System.out.println("Reversed String is: " + reversedString);
}
}
6. Reversing a String Using Java 8 Streams
Java 8 Streams provide a functional approach to reversing strings. The following example demonstrates a way to reverse a string using streams:
javaCopy codeimport java.util.stream.Collectors;
import java.util.stream.IntStream;
public class StringReverse8 {
public static void main(String[] args) {
String string = "Programmer";
String reversedString = IntStream.rangeClosed(1, string.length())
.mapToObj(i -> String.valueOf(string.charAt(string.length() - i)))
.collect(Collectors.joining());
System.out.println("Reversed String is: " + reversedString);
}
}
Additional Ways to Reverse Strings in Java
Using Arrays and Collections
Another approach involves converting a string to an array, reversing it using Collections.reverse(), and joining it back into a string:
javaCopy codeimport java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class StringReverse9 {
public static void main(String[] args) {
String string = "Developer";
String[] characters = string.split("");
List<String> charList = Arrays.asList(characters);
Collections.reverse(charList);
String reversedString = String.join("", charList);
System.out.println("Reversed String is: " + reversedString);
}
}
Using Lambda Expressions and Reduce
Using Java 8’s lambda expressions with the reduce() method also allows for concise string reversal:
import java.util.stream.Stream;
public class StringReverse10 {
public static void main(String[] args) {
String string = "Engineer";
String reversedString = Stream.of(string.split(""))
.reduce("", (reversed, ch) -> ch + reversed);
System.out.println("Reversed String is: " + reversedString);
}
}
Conclusion
Java provides numerous methods to reverse a string, each with different performance characteristics and complexity. From using simple loops to leveraging modern Java 8 Streams and lambda expressions, you can choose the method that best suits your specific needs and code readability.
Understanding various string reversal techniques is essential for Java developers, especially when interviewing or working on tasks where avoiding built-in functions is required. These examples provide a foundation to implement string reversal effectively across different scenarios in Java.