How to Reverse a String in Java

There are a lot of ways to reverse a string in Java. One can use iteration, StringBuilder, StringBuffer to do the reverse of a given string. Let’s see different ways to the string reversal.

By using StringBuilder


Consider the following program.

FileName: StringReverseExample.java

Output:

By using StringBuffer


Consider the following program.

FileName: StringReverseExample1.java

Output:

By using Char Array


Consider the following program.

FileName: StringReverseExample2.java

Output:

Explanation: In the above program, the string is converted into the character array. Then, the character array is traversed from the end to the beginning, i.e., in reverse order to generate the reverse of the given string.

By using the charAt() method

The charAt() has the following syntax.

Syntax:

FileName: StringReverseExample3.java

Output:

Explanation: The charAt(j) method takes returns the character present at the index j. Since the for-loop is iterating from the last index of the string to the first index. Therefore, at first, the character present at the last index gets copied. Then the character present at the penultimate index and so on. After the end of the for-loop, the string ans stores the string, which is the reverse of the string that is passed as the parameter of the method reverseString().

By using stack

Stack can also be used for the reversal of a given string. The following program illustrates the same.

FileName: StringReverseExample4.java

Output:

Explanation: The LIFO (Last In First Out) property of the stack comes in handy to do the reversal of the given string. The for-loop of the reverseString() method puts the characters, one by one, starting from the first index to the last index. Thus, when a character is popped from the stack, the last character comes out first, then the second last character, and so on. Thus, after the end of the while-loop, the string contained in the ans, is the reverse of the string that is passed as the parameter of the method reverseString().

By using recursion

The recursive approach can also be used to do the reverse of the given string. The following program illustrates the same.

FileName: StringReverseExample5.java

Output:

Explanation: Using recursion, first, we are moving to the end of the given string. Then, the concatenation work starts using the + operator with the help of the method charAt(). Thus, at first, the last character, then the second last character gets concatenated, and eventually, we get a reverse of the given string.

Pin It on Pinterest

Share This