Program to reverse a String without using StringBuilder

🔁 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

"My Name is Vinod"

Then the output will be

"doniV si emaN yM"

⚙️ How it works (step by step)

  1. Start with an input string, e.g. "My Name is Vinod".

  2. Initialize an empty string reverse = "".

  3. Loop backward from the end of the string (str.length() - 1) to the beginning (0).

  4. For each character:

    • Append it to reverse.

  5. Once the loop completes, reverse will contain the reversed text.

  6. Print the reversed string.


🧠 Example Walkthrough

StepCurrent IndexCharacterReverse String
115dd
214odo
313ndon
412idoni
511VdoniV
610(space)doniV
Final0MdoniV 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

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts