Coding questionnaires often ask you how to reverse a string in Java, and it shouldn’t be rocket science. It is one of the most popular programming languages for a reason, after all! Currently, Java supports various projects, from back-end databases to mobile apps and more.
Today we will talk about reversing a string in Java, a usual operation and a frequently asked question in logic questionnaires. Every Java developer should know how to reverse a string and, in this guide, we plan to get you there.
We will actually explain many methods here so you can pick the one you feel the most comfortable using, as we think this is the best we can offer you. Without further ado, let’s jump right in!
How to Reverse a String in Java
As in any other programming language, in Java, we define a string as a set of characters.
In Java, string objects are immutable, meaning that they cannot change once they’re created. Therefore, it would be fair to say that a string is closer to a constant than a variable.
Though we can’t modify a string in Java, it’s possible to use the StringBuilder class. Here, we have an alternative that creates a mutable series of characters.
The StringBuilder will be critical when we craft the logic for reversing a string. Luckily, we can use the built-in reverse() method (which Python also has!).
For now, we will use String and StringBuild classes in combination with the usual syntax of Java.
Now that we have introduced these concepts, we can immediately jump to some code examples.
Example #1: StringBuilder
The StringBuilder class is our first choice. For this guide, we’ll assume you’ve already read through our other articles on Java, so you should already have a firm grasp of most of the concepts we’ll discuss here.
First, let’s convert our string to a new mutable object so we can use the built-in reverse() method.
As you can see, the logic is straightforward and easy to understand. Once the conversion is done, we call the reverse() function and make it work in conjunction with the mutable string.
You see how the idea is simple: make the immutable string permeable to the action of the reverse() function.
Finally, we convert the StringBuilder to a usual string and get the reversed text in the output section. This is a rather lengthy method to reverse a string in Java, but it does work.
Example #2: toCharArray()
Next in line, we have a method that calls the toCharArray() in-built function. This tool allows us to convert a string to a character array.
See below how this works:
To reverse the string, we just need to swap the characters, taking the last one and putting it first, and so on. But these instructions only return an array when we need a string.
We need to call the string.valueof() function for the last step, which will return a string from the reversed array.
The conversion to an array might not be the most efficient logic (particularly for newcomers), so let’s see another example without this extra step.
Example #3: Classic For Loop
For our next reversing method, we will use the For Loop, a favorite of every programmer. We’ve already talked about loops in Java in other articles like this one, but it never hurts to revisit foundational concepts.
For Loops are a handy tool present in almost every programming language and fundamental in the architecture of many programs.
In the example below, we will call the For Loop and then iterate through the string we want to reverse.
As you can see in the example, we first iterate through each character using the For Loop. Just before, we declared an empty string and then saved each character, but in the order we needed.
This is a simple and convenient method because, even if we need to write the logic of the For Loop, we are saving a lot of space by not coding any object conversion. Also, we have the advantage of a faster processing time as converting objects usually takes longer and drains more resources.
Example #4: Stack
In Java, the Stack class (part of the Collection framework) models and implements the Stack data structure, meaning last-in-first-out.
Stack comes with many integrated methods, such as pop(). These methods will help us with the reverse string and some other operations. If this is new to you, pay attention! You’ll definitely like it.
Let’s see an example:
We need to import the Stack dependencies on the top of our code. We use push() so the last character gets printed in the right place, and our new string is created.
Reverse a String in Java Using Libraries
With Java, we have access to tons of free-to-access libraries created by its users. These libraries give us new functionalities that are not natively available in Java.
Libraries are a clever way to expand the developing power of any programming language. Now, let’s find out how to use a library for our goal.
The Apache Commons is one of the most popular libraries among Java users. With Apache, we can take advantage of many classes and methods to help us do many things, like reversing a string.
Conveniently for us, there are some classes available for string manipulation.
In this example, we use the StringUtils class found in the Apache Commons library, which includes a reverse() function.
This logic is similar to the one using StringBuilder but uses less code, simplifying the debugging process if anything happens. This is probably the cleanest method we’ve mentioned, but it is impossible using only native functions.
Let’s watch YouTuber Mintype demonstrate how to reverse a string (Hello World!) in Java.
That’s a lot of information, so let’s review what we’ve just learned.
First, we learned about strings and the different types of string objects available in Java.
Then, we used the StringBuilder class for our first solution. The code was simple and easy to understand using the reverse() built-in method. We took a similar approach with the Apache Commons library but now writing an overall simpler syntax.
Next, we built an example using the toCharArray() function. Here, we accomplished our goal, but with many unnecessary extra steps. We needed several object conversions to make our code work with toCharArray().
We also tried using a For Loop, and this was one of the most straightforward solutions. The For Loop lets us iterate through our string and then return the characters in the desired order.
Just like arrays or functions, strings are a fundamental tool, so Java offers a variety of functionalities for every idea involving strings. If you want to learn more, you should always check the official documentation!
Now you have a new tool to improve your projects and programs. So, go ahead and write some code to try out all these new concepts. Good luck!
The image featured at the top of this post is ©Bigc Studio/Shutterstock.com.