Skip to content

Reverse a string in Java

To reverse a string in Java, you can use the following approaches:

  1. Using a for loop:

Best for understanding the underlying logic or when you need custom iteration control.


java
public class Main {
  public static void main(String[] args) {
    String str = "Hello";
    StringBuilder sb = new StringBuilder();

    for (int i = str.length() - 1; i >= 0; i--) {
      sb.append(str.charAt(i));
    }

    String reversed = sb.toString();
    System.out.println(reversed);  // Output: "olleH"
  }
}
  1. Using the reverse method of the StringBuilder class:

Recommended for most cases due to its readability and built-in optimization.


java
public class Main {
  public static void main(String[] args) {
    String str = "Hello";
    String reversed = new StringBuilder(str).reverse().toString();
    System.out.println(reversed);  // Output: "olleH"
  }
}
  1. Using a character array swap:

Ideal for performance-critical scenarios where minimizing object allocation is important.


java
public class Main {
  public static void main(String[] args) {
    String str = "Hello";
    char[] chars = str.toCharArray();
    int left = 0;
    int right = chars.length - 1;
    while (left < right) {
      char temp = chars[left];
      chars[left] = chars[right];
      chars[right] = temp;
      left++;
      right--;
    }
    String reversed = new String(chars);
    System.out.println(reversed);  // Output: "olleH"
  }
}

I hope this helps! Let me know if you have any other questions.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.