In this tutorial you will learn about different ways to reverse string in java with examples.
For example:
Input: Hello World
Output: dlroW olleH
Ways to Reverse String in Java
Method 1:
This is the simplest method in which we iterator through given string from end character by character and append to new empty string.
package com; public class ReverseStringJava { public static void main(String...s){ String str = "I love programming"; String strReverse = ""; System.out.println("Original String: " + str); for(int i = str.length() - 1; i >= 0; --i){ strReverse = strReverse + str.charAt(i); } System.out.println("Reversed String: " + strReverse); } }
Output
Original String: I love programming
Reversed String: gnimmargorp evol I
Method 2:
It is also an iterative method in which we iterate through the string from start as well as end and keep swapping the characters. Below is the program to implement this.
package com; public class ReverseStringJava { public static void main(String...s){ String str = "I love programming"; char strChars[], tempChar; System.out.println("Original String: " + str); strChars = str.toCharArray(); for(int i = 0, j = str.length()-1; i < str.length()/2; ++i, --j){ tempChar = strChars[i]; strChars[i] = strChars[j]; strChars[j] = tempChar; } System.out.print("Reversed String: "); for(char c : strChars){ System.out.print(c); } } }
Method 3:
StringBuffer class provides a method reverse() to reverse a string. This is the fastest and most efficient way to reverse a string.
package com; public class ReverseStringJava { public static void main(String...s){ String str = "I love programming"; StringBuffer strReverse = new StringBuffer(str); System.out.println("Original String: " + str); strReverse.reverse(); System.out.print("Reversed String: " + strReverse); } }
Method 4:
In this method we first insert the characters of string in a linked list. Now reverse the linked list using Collections.reverse() method. Finally print the characters present in linked list.
package com; import java.util.Collections; import java.util.LinkedList; public class ReverseStringJava { public static void main(String...s){ String str = "I love programming"; char strChars[] = str.toCharArray(); LinkedList<Character> list = new LinkedList<Character>(); System.out.println("Original String: " + str); for(char c : strChars){ list.add(c); } Collections.reverse(list); System.out.print("Reversed String: "); for(char c : list){ System.out.print(c); } } }
Please mention in the comment section if you know any other way to reverse string in java.
Push each character onto a stack, then pop em back off.
Stack reverse = new Stack();
String testString = “I love programming in Java”;
char[] charArray = testString.toCharArray();
for(char c:charArray){
reverse.push(c);
}
String reversed = “”;
while(!reverse.isEmpty()){
reversed += (reverse.pop());
}
System.out.println(reversed.toString());
}
Thanks for mentioning this method, I will add it to the tutorial.