How to Reverse String in Java?

How to Reverse String in java

There are a few different ways to reverse a string in Java.

1. Using for loop

We can use a for loop to iterate through the characters of the string from the end to the beginning, and then add each character to a new string.

Example:

String input = "Hello World!";
String reversed = "";

for(int i = input.length() - 1; i >= 0; i--) {
   reversed = reversed + input.charAt(i);
}

System.out.println(reversed); // Output: !dlroW olleH

2. Using StringBuilder class

The StringBuilder class has a reverse() method which can be used to reverse a string.

Example:

String input = "Hello World!";
StringBuilder sb = new StringBuilder(input);
sb.reverse();
String reversed = sb.toString();

System.out.println(reversed); // Output: !dlroW olleH

3. Using ArrayUtils class

The ArrayUtils class from Apache Commons Lang library has a reverse() method which can be used to reverse an array of characters. We can convert the string to an array of characters and then use this method to reverse the array, and then convert it back to a string.

Example:

String input = "Hello World!";
char[] charArray = input.toCharArray();
ArrayUtils.reverse(charArray);
String reversed = new String(charArray);

System.out.println(reversed); // Output: !dlroW olleH

Leave a Reply