Java Program to Reverse a String with Output and Explanation
for (int i = str.length() - 1; i >= 0; i--) reversed += str.charAt(i);.Examples
How to Think About It
Algorithm
Code
public class ReverseString { public static void main(String[] args) { String str = "hello"; String reversed = ""; for (int i = str.length() - 1; i >= 0; i--) { reversed += str.charAt(i); } System.out.println(reversed); } }
Dry Run
Let's trace the string "hello" through the code
Initialize variables
str = "hello", reversed = ""
Start loop from last character
i = 4 (index of 'o')
Append character
reversed = "o"
Next iteration
i = 3 (index of 'l'), reversed = "ol"
Next iteration
i = 2 (index of 'l'), reversed = "oll"
Next iteration
i = 1 (index of 'e'), reversed = "olle"
Next iteration
i = 0 (index of 'h'), reversed = "olleh"
Loop ends
Print reversed string: "olleh"
| i | Character | Reversed String |
|---|---|---|
| 4 | o | o |
| 3 | l | ol |
| 2 | l | oll |
| 1 | e | olle |
| 0 | h | olleh |
Why This Works
Step 1: Loop from end to start
The loop starts at the last character index and moves backward to the first, so characters are accessed in reverse order.
Step 2: Build reversed string
Each character is added to the new string, so the new string grows with characters in reverse order.
Step 3: Print the result
After the loop finishes, the reversed string contains the original string flipped, which is printed.
Alternative Approaches
public class ReverseString { public static void main(String[] args) { String str = "hello"; String reversed = new StringBuilder(str).reverse().toString(); System.out.println(reversed); } }
public class ReverseString { 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("hello")); } }
Complexity: O(n) time, O(n) space
Time Complexity
The program loops through each character once, so the time grows linearly with the string length.
Space Complexity
A new string is created to hold the reversed characters, so space also grows linearly with input size.
Which Approach is Fastest?
Using StringBuilder's reverse() is fastest and most memory efficient compared to manual loops or recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual loop | O(n) | O(n) | Learning and simple control |
| StringBuilder reverse() | O(n) | O(n) | Performance and simplicity |
| Recursion | O(n) | O(n) | Understanding recursion, less efficient |