Back to Java
2026-01-166 min read

Reverse a String

Learn Reverse a String step by step with clear examples and exercises.

Why This Matters

Reverse a string in Java is not just a simple programming task; it serves as a foundation for understanding basic string manipulation and array traversal concepts. These skills are crucial for coding interviews, real-world programming, and debugging common errors. By mastering the art of reversing a string, you will enhance your problem-solving abilities and develop a strong foundation in Java programming.

Prerequisites

To understand how to reverse a string in Java, you should be familiar with:

  1. Basic Java syntax, including variables, operators, and control structures like if, else, and switch.
  2. String manipulation, such as concatenation, length, substring, and comparison operations.
  3. Array traversal techniques, including for loops, array indexing, and multi-dimensional arrays.
  4. Methods and functions, including their declaration, parameters, return types, overloading, and recursion.
  5. Exception handling to manage potential errors during the reversal process.
  6. Data structures like stacks and queues, which can be used for efficient string manipulation.

Core Concept

To reverse a string in Java, we can employ two strategies: iterative and recursive. In this lesson, we will focus on the iterative method for clarity and efficiency.

  1. Declare two variables: start and end, representing the beginning and end of the string.
  2. Initialize an additional variable (e.g., temp) to store characters during the swapping process.
  3. In a loop, swap characters at positions start and end.
  4. Decrement the end index in each iteration until it's less than or equal to the start.
  5. After the loop finishes, the original string will be reversed.

Here is the iterative method code snippet:

public static void reverseString(String str) {
int start = 0;
int end = str.length() - 1;
char temp;

while (start < end) {
// Swap characters at positions start and end
temp = str.charAt(start);
str = str.substring(0, start) + str.charAt(end) + str.substring(start+1, end+1) + str.substring(end);
start++;
end--;
}

System.out.println("Reversed String: " + str);
}

Alternative Iterative Method

Another iterative method to reverse a string without using additional variables is by using two pointers, start and end, and swapping characters directly in the original string:

public static void reverseStringIterative(String str) {
int start = 0;
int end = str.length() - 1;

while (start < end) {
char temp = str.charAt(start);
str = str.substring(0, start) + str.charAt(end) + str.substring(start+1, end) + str.substring(0, end-1);
start++;
end--;
}

System.out.println("Reversed String: " + str);
}

Worked Example

Let's reverse the string "Hello World!" using our iterative method:

public static void main(String[] args) {
String input = "Hello World!";
reverseStringIterative(input);
}

Output:

Reversed String: !dlroW olleH

Recursive Method

To reverse a string recursively, we can split the string into two parts and call the method on each half until we reach the base case (a single character). Here is an example of a recursive method to reverse a given string in Java:

public static void reverseStringRecursive(String str, int start, int end) {
if (start >= end) {
return;
}

char temp = str.charAt(start);
str = str.substring(0, start) + str.charAt(end) + str.substring(start+1, end) + str.substring(0, end-1);
reverseStringRecursive(str, start+1, end-1);
}

To call the recursive method with a string as input, you can use:

public static void reverseStringRecursive(String str) {
reverseStringRecursive(str, 0, str.length() - 1);
}

Common Mistakes

  1. Forgetting to increment or decrement the start or end index in the loop.
  2. Swapping characters outside the string bounds (i.e., accessing invalid array indices).
  3. Using a for-each loop instead of a traditional for loop, which doesn't allow direct access to the array index.
  4. Failing to account for spaces and special characters in the input string.
  5. Not handling empty strings or strings with only one character correctly.
  6. Neglecting to handle potential exceptions during the reversal process.
  7. Misunderstanding the base case for recursive methods, leading to infinite loops or incorrect results.

Common Mistakes - Recursive Method

  1. Failing to update the start and end indices correctly in each recursive call.
  2. Not considering edge cases, such as a single character string or an empty string.
  3. Implementing an inefficient base case that doesn't return the reversed string directly.
  4. Overlooking potential exceptions during the recursive calls.

Practice Questions

  1. Write a recursive method to reverse a given string in Java, handling edge cases like empty strings and single character strings correctly.
  2. Implement an iterative method to reverse a string without using additional variables (temp or substring).
  3. Modify the iterative method to handle palindromes (strings that read the same backward as forward) efficiently.
  4. Write a recursive method to find the longest palindrome in a given string, using the iterative method to reverse substrings.
  5. Implement an efficient iterative method to reverse words in a given sentence while maintaining the original word order.
  6. Create a recursive function that generates all possible permutations of a given string in Java.
  7. Write a recursive method to determine if a given string is a palindrome (reads the same backward as forward) without using additional variables or built-in methods like reverse().
  8. Implement an iterative method to reverse a string using only bitwise operations in Java.
  9. Write a recursive method to find all permutations of a given string that are palindromes in Java.
  10. Create a recursive function to determine if a given string is a rotation (a shift of characters in the original string) of another given string in Java.

FAQ

A: The reverse() method only reverses the order of characters within a substring, not the entire string.

Q: What if my input string contains special characters or numbers? How would that affect the reverse process?

A: Special characters and numbers are treated as part of the string when reversing, so they will be included in the reversed output.

Q: Can I use a for-each loop to reverse a string in Java?

A: No, for-each loops don't provide direct access to array indices, making it difficult to implement an efficient reversal method using this approach. However, you can convert the string to a character array and then use a traditional for loop or recursion.

Q: How can I reverse a string without using any built-in methods like substring() or charAt() in Java?

A: You can implement an iterative method that utilizes bitwise operations to swap characters directly, without the need for additional methods. This approach requires careful handling of edge cases and special characters.

Q: Is there a more efficient way to reverse a string in Java using data structures like stacks or queues?

A: Yes, you can use a stack or queue to store characters from the original string and then pop/dequeue them to build the reversed string. This approach offers better performance for large strings due to its constant time complexity (O(n)).

Q: How would I reverse a string in Java using only one line of code?

A: While it is possible to write a one-liner to reverse a string in Java, the resulting code can be difficult to understand and maintain. It's generally recommended to use more readable and maintainable code over concise one-liners for better long-term project sustainability.

Reverse a String | Java | XQA Learn