0
0
JavaHow-ToBeginner · 3 min read

How to Reverse String in Java: Simple Methods Explained

To reverse a string in Java, you can use the StringBuilder class and its reverse() method, like new StringBuilder(yourString).reverse().toString(). This is the simplest and most efficient way to reverse strings in Java.
📐

Syntax

The common syntax to reverse a string in Java uses the StringBuilder class:

  • new StringBuilder(yourString): Creates a mutable sequence of characters from the original string.
  • reverse(): Reverses the sequence of characters.
  • toString(): Converts the reversed sequence back to a string.
java
String reversed = new StringBuilder(originalString).reverse().toString();
💻

Example

This example shows how to reverse a string using StringBuilder. It prints the original and reversed strings.

java
public class ReverseStringExample {
    public static void main(String[] args) {
        String original = "hello";
        String reversed = new StringBuilder(original).reverse().toString();
        System.out.println("Original: " + original);
        System.out.println("Reversed: " + reversed);
    }
}
Output
Original: hello Reversed: olleh
⚠️

Common Pitfalls

Some common mistakes when reversing strings in Java include:

  • Trying to reverse a string by looping and concatenating characters manually, which is less efficient.
  • Forgetting to convert StringBuilder back to a string using toString().
  • Using StringBuffer unnecessarily when StringBuilder is sufficient for single-threaded use.
java
/* Wrong way: manual concatenation in a loop (inefficient) */
String original = "hello";
String reversed = "";
for (int i = original.length() - 1; i >= 0; i--) {
    reversed += original.charAt(i); // creates new string each loop
}

/* Right way: use StringBuilder */
String reversedCorrect = new StringBuilder(original).reverse().toString();
📊

Quick Reference

Summary tips for reversing strings in Java:

  • Use StringBuilder.reverse() for simplicity and performance.
  • Remember to call toString() after reversing.
  • Avoid manual string concatenation in loops for reversing.

Key Takeaways

Use StringBuilder's reverse() method to reverse strings efficiently in Java.
Always convert StringBuilder back to String with toString() after reversing.
Avoid manual string concatenation in loops as it is inefficient.
StringBuilder is preferred over StringBuffer for single-threaded string reversal.