0
0
JavaProgramBeginner · 2 min read

Java Program to Reverse a String with Output and Explanation

You can reverse a string in Java by using a loop to append characters from the end to the start, for example: for (int i = str.length() - 1; i >= 0; i--) reversed += str.charAt(i);.
📋

Examples

Inputhello
Outputolleh
InputJava
OutputavaJ
Input
Output
🧠

How to Think About It

To reverse a string, think of reading the characters from the last one to the first one and building a new string by adding each character in that order. This way, the original order is flipped.
📐

Algorithm

1
Get the input string.
2
Create an empty string to hold the reversed result.
3
Start from the last character of the input string and move backward to the first character.
4
Add each character to the reversed string.
5
Return or print the reversed string.
💻

Code

java
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);
    }
}
Output
olleh
🔍

Dry Run

Let's trace the string "hello" through the code

1

Initialize variables

str = "hello", reversed = ""

2

Start loop from last character

i = 4 (index of 'o')

3

Append character

reversed = "o"

4

Next iteration

i = 3 (index of 'l'), reversed = "ol"

5

Next iteration

i = 2 (index of 'l'), reversed = "oll"

6

Next iteration

i = 1 (index of 'e'), reversed = "olle"

7

Next iteration

i = 0 (index of 'h'), reversed = "olleh"

8

Loop ends

Print reversed string: "olleh"

iCharacterReversed String
4oo
3lol
2loll
1eolle
0holleh
💡

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

Using StringBuilder reverse() method
java
public class ReverseString {
    public static void main(String[] args) {
        String str = "hello";
        String reversed = new StringBuilder(str).reverse().toString();
        System.out.println(reversed);
    }
}
This method is shorter and more efficient because StringBuilder is optimized for string manipulation.
Using recursion
java
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"));
    }
}
This method uses recursion to reverse the string but can be less efficient for very long strings due to call stack overhead.

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.

ApproachTimeSpaceBest For
Manual loopO(n)O(n)Learning and simple control
StringBuilder reverse()O(n)O(n)Performance and simplicity
RecursionO(n)O(n)Understanding recursion, less efficient
💡
Use StringBuilder's reverse() method for a simple and fast way to reverse strings in Java.
⚠️
Beginners often try to modify the original string directly, but strings in Java are immutable, so you must create a new reversed string.