Learn How to Work with Java Reverse String

java reverse stringTo reverse a string means to rearrange the order of the characters by flipping them from the last character to the first. Java provides an API to make it easier to accomplish this task. By using the String Buffer class and its reverse () method, you will be able to reverse the given string in Java.

New to Java? Learn the language at Udemy.com.

Java’s design is to learn as long as you understand the concepts of Object-Oriented Programming (OOP). Much of its syntax was derived from C and C++, so if you have experience with either, then it would be so much easier to get used to Java. However, it does have a lot fewer low-level facilities that the other two had.

One of the finest characteristics of Java is its portability. This means that programs that are created using the Java programming language must run in the same way regardless of what hardware or platform is used. This is possible because of intermediate representation of the language which they call Java bytecode.

Reversing Strings in Java

Before we go to the very convenient methods of the Java string libraries, let’s try to use more manual and literal methods to be able to understand more of what is happening under the hood and how the strings are really being manipulated behind the one-liners.

Reverse By Recursion

One way to reverse a string is using recursion. Recursion is the repeated invocation of a method. See the sample code below:

public static String reverseStringUsingRecursionSample(String sampleStr)

{
String rightString = "";String leftString = "";

int len = sampleStr.length();

if (len <= 1) return sampleStr;

leftString = sampleStr.substring(0, len / 2);

rightString = sampleStr.substring(len / 2, len);

return reverseStringUsingRecursionSample(rightString) + reverseStringUsingRecursionSample(leftString);
}

First, the length of the string is determined. If the string only has one character, or it is empty, the recursion returns the original string and the recursion is not repeated anymore. If not, the leftString variable is assigned half of the original string and the other half is assigned to the rightString variable.  Then the method passes the concatenation of rightString again to the same method which is then added to the leftString (also passed to the same method) until the whole string is done being reversed.

Java beginner? Learn how to use the language at Udemy.com.

For a clearer idea of what is going on, let’s say we’re using the string “JAVA” in the program:

First pass                     len = 4

leftString = “JA”

rightString = “VA”

return “VA” + “JA”

 

The strings “VA” and “JA” both go through the same method:

 

“VA”                            len = 2

leftString = “V”

rightString = “A”

return “A” + “V”

 

“JA”                             len = 2

leftString = “J”

rightString = “A”

return “A” + “J”

If “A” is passed to the reverseStringUsingRecursionSample() method, it will only be returned as-is. Therefore, the recursion in this portion of the string is finished. Since in the first pass, leftString is “VA” whose reverse is “A” + “V” and right string, “JA”, has the result “A” + “J”, the final pass will give you “A” + “V” + “A” + “J”.

Reverse by charAt() Function

Another way is by looping through the characters in the string you want to reverse by using the charAt() function to reposition them one by one. Sample code:

public static String reverseStringUsingCharAtSample(String sampleStr)
{               
int len = sampleStr.length();               
String strReversed = "";               
for (int i = 0; i < len; i++)    {                            
strReversed = sampleStr.charAt(i) + strReversed;               
return strReversed; }
}

First, the length of the whole string is assigned to the variable len, then a container for the reversed string (strReversed) is declared as empty. Then, using a for loop, in which i is initialized as 0 and the iteration limit is the string length less 1, the function charAt() is used to get the character in the index i then saved into the variable strReversed added to the current value of strReversed.

Again using the string “JAVA”, here is a more detailed example:

1st Pass            – charAt(0)     strReversed = “J” + “”             =          “J”

2nd Pass – charAt(1)    strReversed = “A” + “J”          =          “AJ”

3rd Pass – charAt(2)     strReversed = “V” + “AJ”        =          “VAJ”

4th Pass – charAt(3)     strReversed = “A” + “VAJ”      =          “AVAJ”

loop ends

Reverse by Character Array

This method makes use of the toCharArray() function. It is similar to how the charAt() method was used but instead of starting from the first index character, you will start from the last and keep on adding the rest of the letters in reversed order. Sample code:

public static String reverseStringUsingCharArraySample(String sampleStr)
{               
char[] charArray = sampleStr.toCharArray();               
String reversedStr = "";               
for (int i = charArray.length - 1; i >= 0; i--)      {                          
reversedStr += charArray[i];                              
return reversedStr; }
}

So the difference is if you look at the initialization of the integer “i,” it was assigned the value of the length of sampleStr less 1, which was converted into a character array – meaning you will get the last character of the string first. The limit of the loop is 0 and instead of an increment of 1, the for loop uses a decrement of 1, denoting its backwards flow.

With the string “JAVA”, here is the progression:

1st Pass – charArray[3]            reversedStr = “A”                    = “A”

2nd Pass – charArray[2]           reversedStr = “A” + “V”          = “AV”

3rd Pass – charArray[1]           reversedStr = “A” + “AV”        = “AVA”

4th Pass – charArray[0]           reversedStr = “J” + “AVA”      = “AVAJ”

Reverse by String Buffer

The most convenient of all the given methods is the StringBuffer() function in Java. It just takes one line of code to provide you with the reversed version of your original string. See sample code:

String originalString = "JAVA";

String reversedString = new StringBuffer(originalString).reverse().toString();

Just declare a container variable for your output and pass the original string to the StringBuffer() method. The desired output will be returned and assigned to the container. (Start learning Java here)

And that’s it. This is all you have to do to be able to extract a reversed version of your string. Don’t make things hard for yourself especially when Java has made things very convenient for you as a programmer. So utilize it. It will only be practical to use the other methods mentioned above when there are other particular things that you’d like to alter or manipulate in the string or the characters in each index. If not, stick to the optimized one already made for you.