Visit Sponsor

Written by 12:32 pm Core Java

Reverse String in Java – Examples & Best Practices

Reversing a string in Java is a common requirement in text manipulation, algorithm design, and interview scenarios. Although Strings in Java are immutable, multiple techniques exist to reverse text efficiently using core APIs, utilities, and modern constructs.

This updated guide on javatechig.com presents various Java string reversal approaches with complete examples, performance insights, edge‑case handling, and best practices.

What Does “Reverse String” Mean?

Reversing a string means producing a new sequence of characters in the opposite order of the original.

Example:

“JAVA” → “AVAJ”

Because String is immutable in Java, reversal involves creating new sequences rather than modifying the original string.

Method 1 — Using StringBuilder (Recommended)

Java Example

public static String reverseWithStringBuilder(String input) {
    return new StringBuilder(input).reverse().toString();
}

Why prefer this?

  • Efficient for small to medium strings
  • Uses built‑in reverse implementation
  • Simple and readable

Method 2 — Classic Loop (Manual)

Java Example

public static String reverseWithLoop(String input) {
    char[] chars = input.toCharArray();
    String result = "";
    for (int i = chars.length - 1; i >= 0; i--) {
        result += chars[i];
    }
    return result;
}

Note: This approach is less efficient due to repeated string concatenation and should be used for educational demonstration only.

Method 3 — Using Character Array

Java Example

public static String reverseWithCharArray(String input) {
    char[] array = input.toCharArray();
    int left = 0, right = array.length - 1;
    while (left < right) {
        char temp = array[left];
        array[left] = array[right];
        array[right] = temp;
        left++;
        right--;
    }
    return new String(array);
}

This method avoids intermediate string concatenation and is efficient for medium‑sized strings.

Method 4 — Recursion

Java Example

public static String reverseWithRecursion(String input) {
    if (input == null || input.length() <= 1) {
        return input;
    }
    return reverseWithRecursion(input.substring(1)) + input.charAt(0);
}

Good for learning recursion, but not optimal for long strings due to call stack overhead.

Method 5 — Java Stream (Java 8+)

Java Example

public static String reverseWithStreams(String input) {
    return IntStream.rangeClosed(1, input.length())
            .mapToObj(i -> String.valueOf(input.charAt(input.length() - i)))
            .collect(Collectors.joining());
}

Streams provide expressive code but may be slower than StringBuilder in performance‑critical scenarios.

Handling Edge Cases

Empty or Null Strings

if (input == null || input.isEmpty()) {
    return input;
}

Always check for null to avoid NullPointerException.

Unicode and Surrogate Pairs

When reversing Unicode text with surrogate pairs (like emojis), consider code point based reversal:

public static String reverseByCodePoint(String input) {
    int[] cps = input.codePoints().toArray();
    StringBuilder sb = new StringBuilder();
    for (int i = cps.length - 1; i >= 0; i--) {
        sb.appendCodePoint(cps[i]);
    }
    return sb.toString();
}

This preserves Unicode correctness for multi‑unit characters.

Performance Comparison

MethodTime ComplexityNotes
StringBuilderO(n)Most efficient
Char ArrayO(n)Efficient and manual
Loop + concatO(n²)Inefficient
RecursionO(n²)Memory‑intensive
StreamsO(n)Expressive, moderate performance

When to Use Each Method

  • StringBuilder: Best general use
  • Char Array: Manual, efficient
  • Loop: Educational
  • Recursion: Concept learning
  • Streams: Functional style

Practical Examples

Reverse and Compare

String s1 = "level";
String reversed = reverseWithStringBuilder(s1);
boolean isPalindrome = s1.equalsIgnoreCase(reversed);

This demonstrates evaluating palindromes.

Best Practices (2026 Updated)

  • Prefer StringBuilder for most reversal needs
  • Use code point logic for Unicode correctness
  • Avoid string concatenation in loops for performance
  • Handle null and empty inputs explicitly
Visited 10 times, 1 visit(s) today
Close