How to Reverse a String in Java [2021]
This tutorial will show how to reverse a string in java using 7 different ways.
how to reverse a string in java is a very common question that is being asked in interviews and also with different methods as there is no inbuilt method in the String class for string reversal.
Few facts about String class
1. String class is immutable thus any change in string instance creates a new string object.
2. StringBuffer/StringBuilder class has an inbuilt reverse() method.
3. As StringBuffer is synchronized so StringBuilder is preferred over StringBuffer.
So let's get started...
Here are the 7 different ways to reverse a string in java
- Reverse a string in java using for loop.
- Reverse a string in java using recursion.
- Using the built-in string reverse function in java of StringBuilder class/StringBuffer class.
- Converting String to Character Array and then swapping with iteration.
- Reverse string using the charAt method.
- Reverse a string in java 8.
- Reverse a string in java using Apache commons library.
Added Bonus: How to reverse a string in java word by word
Let's discuss them one by one
1. Reverse a string in java using for loop
The same code can be used if someone asks how to reverse a string in java without using the reverse function.
In this process, we follow two steps
1. Convert string to character array using the toCharArray() method.
2. Iterate character array in reverse order and append to the string.
Example
public class ReverseStringUsingIteration {
public static void main(String[] args) {
String testString = "javacodegeek";
System.out.println("Actual String : " + testString);
String reversed = reverse(testString);
System.out.println("Reversed String : " + reversed);
}
private static String reverse(String testString) {
char charArray[] = testString.toCharArray();
String reversedString = "";
for (int index = charArray.length - 1; index >= 0; index--) {
reversedString += charArray[index];
}
return reversedString;
}
}
Output:
Actual String : javacodegeek
Reversed String : keegedocavaj
2. Reverse a string in java using recursion
The same code can be used if someone asks how to reverse a string in java without using the reverse function.
In this process, a recursion mechanism is being used to reverse a string.
Example:
public class ReverseStringUsingRecursion {
public static void main(String[] args) {
String testString = "javacodegeek";
System.out.println("Actual String : " + testString);
String reversed = reverse(testString);
System.out.println("Reversed String : " + reversed);
}
private static String reverse(String testString) {
if (testString.length() == 0)
return " ";
return testString.charAt(testString.length() - 1)
+ reverse(testString.substring(0, testString.length() - 1));
}
}
Output:
Actual String : javacodegeek
Reversed String : keegedocavaj
3. Using the built-in string reverse function in java of StringBuilder class/StringBuffer class
StringBuffer and StringBuilder have a reverse() method which is used to reverse the characters. This method replaces the character sequence in the reverse order.
Both StringBuilder and StringBuffer has the same approach of reversing a String in Java. But, StringBuilder is preferred as it is not synchronized and is faster than StringBuffer.
StringBuilder Example:
public class ReverseString1 {
public static void main(String[] args) {
String testString = "javacodegeek";
System.out.println("Actual String : " + testString);
String reversed = reverse(testString);
System.out.println("Reversed String : " + reversed);
}
private static String reverse(String testString) {
StringBuilder builder = new StringBuilder(testString);
return builder.reverse().toString();
}
}
Output:
Actual String : javacodegeek
Reversed String : keegedocavaj
StringBuffer Example:
public class ReverseString2 {
public static void main(String[] args) {
String testString = "javacodegeek";
System.out.println("Actual String : " + testString);
String reversed = reverse(testString);
System.out.println("Reversed String : " + reversed);
}
private static String reverse(String testString) {
StringBuffer buffer = new StringBuffer(testString);
return buffer.reverse().toString();
}
}
Output:
Actual String : javacodegeek
Reversed String : keegedocavaj
4. Converting String to Character Array and then swapping with iteration
This approach will simply convert String to Character array using toCharArray() and then swapping the first and last characters by position using two indexes to reverse the string.
Example:
public class ReverseStringUsingIterationWithSwapping {
public static void main(String[] args) {
String testString = "javacodegeek";
System.out.println("Actual String : " + testString);
String reversed = reverse(testString);
System.out.println("Reversed String : " + reversed);
}
private static String reverse(String testString) {
char[] charArray = testString.toCharArray();
int leftIndex = 0;
int rightIndex = charArray.length - 1;
for (leftIndex = 0; leftIndex < rightIndex; leftIndex++, rightIndex--) {
char temp = charArray[leftIndex];
charArray[leftIndex] = charArray[rightIndex];
charArray[rightIndex] = temp;
}
return String.valueOf(charArray);
}
}
Output:
Actual String : javacodegeek
Reversed String : keegedocavaj
5. Reverse String using the charAt method
In this approach, we will see how to reverse a string in java using a scanner with the help of the String class charAt() method.
Example:
public class ReverseStringUsingCharAt {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the input string to reverse");
String input = in.nextLine();
String reversed = reverse(input);
System.out.println("Reversed string : " + reversed);
}
private static String reverse(String testString) {
String reversed = "";
for (int i = testString.length() - 1; i >= 0; i--) {
reversed = reversed + testString.charAt(i);
}
return reversed;
}
}
Output:
Enter the input string to reverse
javacodegeek
Reversed string : keegedocavaj
6. Reverse a string in java 8
In this approach, we will use Java 8 features using IntStream, map, and other features to reverse a string.
Example:
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ReverseStringUsingJava8 {
public static void main(String[] args) {
String testString = "javacodegeek";
System.out.println("Actual String : " + testString);
String reversed = reverse(testString);
System.out.println("Reversed String : " + reversed);
}
private static String reverse(String testString) {
return IntStream.range(0, testString.length())
.mapToObj(x-> testString.charAt((testString.length()-1) - x))
.map(character -> String.valueOf(character))
.collect(Collectors.joining(""));
}
}
Output:
Actual String : javacodegeek
Reversed String : keegedocavaj
7. Reverse a string in java using Apache commons library
In this approach, we will use the apache commons library which is a third-party library to reverse a string. We need to import dependencies for this. Below is the dependency which we need to include in pom.xml.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3. 11</version>
</dependency>
Example:
import org.apache.commons.lang3.StringUtils;
public class ReverseStringUsingCommons {
public static void main(String[] args) {
String testString = "javacodegeek";
System.out.println("Actual String : " + testString);
String reversed = StringUtils.reverse(testString);
System.out.println("Reversed String : " + reversed);
}
}
Output:
Actual String : javacodegeek
Reversed String : keegedocavaj
How to reverse a string in java word by word
This code will show how to reverse a string in java word by word rather than fully reversing the sentence we will only reverse the words in the sentence keeping their position the same.
In this example, we have to first convert string to array and then reverse word at each index using any process we used earlier in this tutorial.
Example:
public class reversestringwordbyword {
public static void main(String[] args) {
String testString = "Welcome To Javacodegeek";
System.out.println("Actual String Word by Word : " + testString);
String reversed = reverseWordByWord(testString);
System.out.println("Reversed String Word by Word : " + reversed);
}
private static String reverseWordByWord(String testString) {
String[] strArray = testString.split(" ");
String reversed = " ";
for (int i = 0; i < strArray.length; i++) {
char[] s1 = strArray[i].toCharArray();
for (int j = s1.length - 1; j >= 0; j--) {
reversed = reversed + String.valueOf(s1[j]);
}
reversed = reversed + " ";
}
return reversed;
}
}
Output:
Actual String Word by Word : Welcome To Javacodegeek
Reversed String Word by Word : emocleW oT keegedocavaJ
Conclusion
That's all about how to reverse a String in Java. In this tutorial, we discuss the 7 different ways to reverse a string in java and an added bonus program to reverse the string in java word by word.
Thanks for reading this tutorial so far. If you like this tutorial then please share it with your friends and colleagues. If you have any questions, doubts, suggestions, or feedback then please drop a comment and I'll try to answer your question.
Happy Learning!!!
More Examples you may like
Comments
Post a Comment
If you have any doubts, Please let me know.