🔁 Reverse a String in Java (Without Using StringBuilder.reverse())
🧩 What problem are we solving?
The goal is to reverse the characters of a given string manually — without using built-in helper methods like StringBuilder.reverse().
This exercise helps understand string manipulation, loops, and index-based access in Java.
For example:
If the input is
Then the output will be
⚙️ How it works (step by step)
-
Start with an input string, e.g.
"My Name is Vinod". -
Initialize an empty string
reverse = "". -
Loop backward from the end of the string (
str.length() - 1) to the beginning (0). -
For each character:
-
Append it to
reverse.
-
-
Once the loop completes,
reversewill contain the reversed text. -
Print the reversed string.
🧠 Example Walkthrough
| Step | Current Index | Character | Reverse String |
|---|---|---|---|
| 1 | 15 | d | d |
| 2 | 14 | o | do |
| 3 | 13 | n | don |
| 4 | 12 | i | doni |
| 5 | 11 | V | doniV |
| 6 | 10 | (space) | doniV |
| … | … | … | … |
| Final | 0 | M | doniV si emaN yM |
✅ Final Output:
doniV si emaN yM
package com.vinod.test;
/**
* Example to reverse a String without using StringBuilder reverse method.
*@authorvinodkariyathungalkumaran
*
*/
public class ReverseStringExample {
public static void main(String[] args) {
String str = "My Name is Vinod";
System.out.println("Input=" + str);
String reverse = "";
for (int i = str.length() - 1; i >= 0; i--) {
reverse = reverse + str.charAt(i);
}
System.out.println("Output=" + reverse);
}
}
Ouput
Input=My Name is Vinod
Output=doniV si emaN yM
No comments:
Post a Comment