Reverse a String in Java
In this lesson: Reverse a string in Java using loop, StringBuilder and char array — code, dry run and output. In Hindi & English.
Reversing a string
Reversing a string means writing its characters back to front — "Java" becomes "avaJ". Because Java strings are immutable, you always build a new reversed string. We will do it with a loop (to learn the logic) and with StringBuilder (the easy way).
Reversing with a loop
public class Reverse {
public static void main(String[] args) {
String str = "Java";
String rev = "";
for (int i = str.length() - 1; i >= 0; i--) {
rev += str.charAt(i); // add chars from the end
}
System.out.println(rev);
}
}
We start at the last index (length() - 1) and move down to 0, reading each character with charAt(i) and adding it to rev. Reading back-to-front gives the reverse.
Dry run
| i | str.charAt(i) | rev += char |
|---|---|---|
| 3 | a | "a" |
| 2 | v | "av" |
| 1 | a | "ava" |
| 0 | J | "avaJ" |
| Loop stops at i<0. Reverse = "avaJ" | ||
The loop reads characters from the last index down to 0 and adds each to rev. So "Java" is read as a, v, a, J — building "avaJ".
Using StringBuilder
String str = "Java"; String rev = new StringBuilder(str).reverse().toString(); System.out.println(rev);
StringBuilder has a built-in reverse() method. This one line is the simplest and most efficient way in real code — no loop needed.
Which method to use
- StringBuilder.reverse() — best for real code: short and fast.
- Loop with charAt — best for learning how reversal works.
Both produce the same result. Use the loop to understand, and StringBuilder in practice.
Common mistakes
- Starting the loop at length(). The last index is
length() - 1. - Trying to change the string in place. Strings are immutable — build a new one.
- Looping upward. To reverse, go from the last index down to 0.
- Slow
+=for very long strings. Use StringBuilder for efficiency.
Summary
- Reversing writes a string's characters back to front.
- Strings are immutable, so you build a new reversed string.
- A loop reads from
length()-1down to 0 withcharAt. new StringBuilder(str).reverse().toString()is the easy way.- Use the loop to learn, StringBuilder in real code.
Next, use this in a palindrome check, or learn text tools in String vs StringBuilder.
Frequently Asked Questions
How do I reverse a string in Java?
new StringBuilder(str).reverse().toString(). To understand the logic, you can also loop from the last character to the first, building a new string. Both give the reversed text.Why can I not reverse a String in place?
How does the loop method reverse a string?
What is the fastest way to reverse a string?
reverse() method is the simplest and efficient choice for real code. The manual loop is mainly for learning how reversal works.How do I get a character at a position?
str.charAt(i), where i is the index starting from 0. The last character is at str.length() - 1. This is how the loop reads each character.