Reverse a String in Java

There are many ways to reverse a String in Java. We will explore how to reverse a String using the StringBuilder class and the for loop (iteration).

Reverse a String in Java using the StringBuilder class

We need to create a new StringBuilder object using the String that we want to reverse and then call the reverse() method. After that, we need to call the toString() method to convert the StringBuilder object back to String.

Example:

public class Test {

  public static void main(String[] args) {

    String stringToReverse = "Hello World of Java!";

    StringBuilder stringBuilder = new StringBuilder(stringToReverse);

    String result = stringBuilder.reverse().toString();

    System.out.println(result);

  }
}
Output: !avaJ fo dlroW olleH
 
We can do the same using the StringBuffer class since it also has the reverse() method.

Reverse a String using the for loop

The following example shows how we can reverse a String using the for loop:

public class Test {

  public static void main(String[] args) {
    String reversedString = "";

    String stringToReverse = "Hello World of Java!";

    char[] array = stringToReverse.toCharArray();

    // reversed iteration
    for (int i = array.length - 1; i >= 0; i--) {
      reversedString += array[i];
    }

    System.out.println(reversedString);

  }
}
Output: !avaJ fo dlroW olleH
 
Happy coding!

Leave a Reply

Your email address will not be published.