For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
Reversing a string simply means flipping its characters so the last character becomes the first, and so on. This is a popular problem in Java programming, often seen in coding interviews, algorithm challenges, and data transformation tasks.
It's not just a basic programming exercise but also a great way to explore core Java concepts like strings, loops, recursion, arrays, and data structures. In this blog, we’ll walk through 11 efficient ways to reverse a string in Java, complete with working code, output, and explanations.
Whether you're a beginner learning Java or someone brushing up before an interview, this guide has you covered. Software engineering courses can help you master Java basics and core concepts faster.
In Java, string reversal is the process of rearranging the characters of a string in reverse order. For instance, reversing "Java" gives "avaJ". It’s commonly used in interview questions to test logic-building and understanding of strings.
Java strings are immutable, meaning you can’t change them after creation. That’s why most string reversal techniques create a new string or use mutable classes like StringBuilder.
This method uses a loop to traverse the string from the end to the beginning, appending each character to a new string. It’s simple but inefficient due to the immutability of strings, which creates a new string each time, making it slow for large strings.
Best for: Beginners or quick logic checks.
public class ReverseString1 {
public static void main(String[] args) {
String input = "Java";
String reversed = "";
for (int i = input.length() - 1; i >= 0; i--) {
reversed += input.charAt(i);
}
System.out.println(reversed);
}
}
Output:
avaJ
Explanation: We loop through the string in reverse and append each character to a new string.
Sharpen your expertise by enrolling in these recommended courses.
StringBuilder is a mutable object, making it an ideal choice for string manipulation. Using its reverse() method, you can reverse a string in a single line. This approach is fast, simple, and works well for most scenarios, especially when you need efficiency and readability.
Best for: Beginners and interview scenarios.
public class ReverseString2 {
public static void main(String[] args) {
String input = "OpenAI";
StringBuilder sb = new StringBuilder(input);
System.out.println(sb.reverse());
}
}
Output:
IAnepO
Explanation: StringBuilder.reverse() directly reverses the string in one line using an internal char array.
Must explore: StringBuffer and StringBuilder Difference in Java
Similar to StringBuilder, StringBuffer offers the reverse() method but with the added benefit of thread safety. If multiple threads need to manipulate the string concurrently, StringBuffer is a better option. Otherwise, StringBuilder is often preferred for better performance in single-threaded environments.
Best for: Thread-safe applications.
public class ReverseString3 {
public static void main(String[] args) {
String input = "Code";
StringBuffer sb = new StringBuffer(input);
System.out.println(sb.reverse());
}
}
Output:
edoC
Explanation: Works just like StringBuilder, but ensures thread safety for concurrent tasks.
Also explore: Strings in Java Vs Strings in Cpp
This method manually reverses a string by converting it to a character array and swapping characters from both ends. It’s memory-efficient since it doesn’t create new strings but rather manipulates the array in-place. It’s a good option for optimizing space in larger strings.
Best for: Memory efficiency and in-place logic.
public class ReverseString4 {
public static void main(String[] args) {
String input = "Hello";
char[] chars = input.toCharArray();
int left = 0, right = chars.length - 1;
while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
System.out.println(new String(chars));
}
}
Output:
olleH
Explanation: This approach reverses the characters in-place using a temporary variable for swapping.
Must check: Char array to string in Java
In this approach, you convert the string to a list of characters, then use Collections.reverse() to reverse the list. While it’s easy to implement and demonstrates the use of collections, it’s not the most efficient method due to extra memory usage for storing the list.
Best for: Demonstrating collection manipulation.
import java.util.*;
public class ReverseString5 {
public static void main(String[] args) {
String input = "World";
List<Character> charList = new ArrayList<>();
for (char c : input.toCharArray()) {
charList.add(c);
}
Collections.reverse(charList);
for (char c : charList) {
System.out.print(c);
}
}
}
Output:
dlroW
Explanation: We convert the string to a character list, reverse it, and print each character.
A stack follows the Last In First Out (LIFO) principle. By pushing each character of the string onto a stack and then popping it off, you can reverse the string. This method illustrates the stack data structure but is less efficient due to extra space used by the stack.
Best for: Learning data structure behavior.
import java.util.*;
public class ReverseString6 {
public static void main(String[] args) {
String input = "Stack";
Stack<Character> stack = new Stack<>();
for (char c : input.toCharArray()) {
stack.push(c);
}
while (!stack.isEmpty()) {
System.out.print(stack.pop());
}
}
}
Output:
kcatS
Explanation: Characters are pushed into a stack and popped in reverse order to form the output.
Recursion in Java, works by breaking down the problem into smaller parts and reversing them step by step. It’s elegant and demonstrates recursion but isn’t ideal for large strings. The risk of stack overflow arises with long strings, so it’s more of an educational approach than a practical one.
Best for: Understanding recursion, not large strings.
public class ReverseString7 {
public static String reverse(String str) {
if (str.isEmpty()) return str;
return reverse(str.substring(1)) + str.charAt(0);
}
public static void main(String[] args) {
System.out.println(reverse("Recursion"));
}
}
Output:
noisruceR
Explanation: This function repeatedly removes the first character and adds it at the end recursively.
Converting the string to a byte array allows manipulation at the byte level. The string is reversed by rearranging the bytes, and the result is returned as a new string. It’s a good method for handling data at a lower level but doesn’t offer significant performance benefits over others.
Best for: Byte-level operations.
public class ReverseString8 {
public static void main(String[] args) {
String input = "Byte";
byte[] strAsByteArray = input.getBytes();
byte[] result = new byte[strAsByteArray.length];
for (int i = 0; i < strAsByteArray.length; i++) {
result[i] = strAsByteArray[strAsByteArray.length - i - 1];
}
System.out.println(new String(result));
}
}
Output:
etyB
Explanation: Each byte is stored in reverse order in a new byte array and converted back to a string.
The XOR swap method allows reversing characters without an auxiliary variable. By using XOR operations, you swap characters in-place. While it’s an interesting and efficient technique in terms of memory usage, it’s more academic and rarely used in real-world applications due to its complexity and reduced readability.
Best for: Bit manipulation interviews.
public class ReverseString9 {
public static void main(String[] args) {
String input = "Bitwise";
char[] arr = input.toCharArray();
int i = 0, j = arr.length - 1;
while (i < j) {
arr[i] ^= arr[j];
arr[j] ^= arr[i];
arr[i] ^= arr[j];
i++;
j--;
}
System.out.println(new String(arr));
}
}
Output:
esiwtiB
Explanation: XOR swaps two characters without using a temp variable, reversing the string in-place.
The Java 8 Streams API introduces a functional style of programming. Using streams, characters are processed, reversed, and collected in a new string. This method is modern, concise, and works well in environments that prioritize functional programming but might be overkill for simpler use cases.
Best for: Writing clean, Java 8+ compatible code.
import java.util.stream.*;
public class ReverseString10 {
public static void main(String[] args) {
String input = "Stream";
String reversed = IntStream.rangeClosed(1, input.length())
.mapToObj(i -> input.charAt(input.length() - i))
.map(String::valueOf)
.collect(Collectors.joining());
System.out.println(reversed);
}
}
Output:
maertS
Explanation: Java Streams reverse the characters using range and collector in a concise one-liner.
Each method has its pros and cons. Here’s a quick comparison:
Method | Time Complexity | Space Complexity | Notes |
String Concatenation | O(n²) | O(n) | Inefficient due to immutability |
StringBuilder.reverse() | O(n) | O(n) | Most efficient and simple |
StringBuffer.reverse() | O(n) | O(n) | Thread-safe |
Char Array Swap | O(n) | O(n) | In-place, efficient |
Collections.reverse() | O(n) | O(n) | More verbose |
Stack | O(n) | O(n) | LIFO logic demonstration |
Recursion | O(n) | O(n) | Stack Overflow risk |
Byte Array | O(n) | O(n) | Byte-level demo |
XOR Swapping | O(n) | O(n) | Tricky but efficient |
Java 8 Streams | O(n) | O(n) | Clean, modern |
We explored different ways to reverse a string in Java, from simple loops and arrays to recursion, streams, and even bitwise operations. Each method offers something unique — from simplicity to performance to learning data structures.
Choose a method based on your use case: readability, speed, or memory optimization. String reversal isn’t just an interview question — it’s a gateway into deeper Java programming concepts.
Yes, you can reverse a string manually using loops and character arrays. This approach involves iterating over the string from the end to the start and appending characters to form a new string without relying on Java's built-in methods like reverse().
String in Java is immutable for security, thread-safety, and performance reasons. Once created, a string's value cannot be changed, which helps avoid unexpected bugs, especially in multithreaded environments or while working with sensitive data like URLs, passwords, or file paths.
Both are mutable classes for string manipulation. StringBuilder is faster but not thread-safe, making it suitable for single-threaded tasks. StringBuffer is thread-safe due to synchronized methods, so it’s preferred when multiple threads might access or modify the same string object.
Avoid recursion when dealing with long strings, as it can lead to StackOverflowError. Recursion consumes additional stack memory for each call, making it less efficient and riskier for large-scale string processing compared to iterative methods or built-in functions.
A stack follows the Last-In-First-Out (LIFO) order. When you push characters of a string onto the stack and then pop them, the characters come out in reverse order. It’s a great way to understand stack operations, though not the most memory-efficient.
It depends on the method. If you use character arrays and swap characters from both ends, it's in-place. However, methods involving new strings or data structures like StringBuilder, lists, or stacks are not in-place as they require extra memory allocation.
Yes, Java 8 introduced the Streams API, which allows you to reverse a string using streams, Collectors.joining(), and String.chars() or String.codePoints(). It’s a functional programming approach and works well when readability and modern syntax are priorities.
No, strings in Java are immutable. Any method that appears to reverse a string actually returns a new string. The original string remains unchanged unless you’re using mutable classes like StringBuilder or working directly with character arrays.
Most methods like StringBuilder.reverse(), loops, and character swapping have O(n) time complexity. Stack and recursion-based approaches also run in O(n) time but may use extra space, affecting space complexity. Byte array and XOR swap methods also follow O(n) time.
Yes, Unicode characters may span more than one char in Java due to surrogate pairs. Standard reversal using char[] or StringBuilder might break such characters. Use codePointAt() and codePoints() to safely reverse strings containing Unicode characters like emojis or special symbols.
Yes, XOR can be used to swap characters in-place without a temporary variable. It works at the bit level and can reverse a string efficiently. However, it’s complex and not readable, so it’s mainly used in academic contexts or competitive programming.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.