Reverse a word
YAJC become Java programmer
Hello! 👋
In this short post we will solve a typical task in programming which is given to every beginner.
Task
You are given a word, you need to reverse it.
Examples: word → drow; radar → radar; sequence → ecneuqes;
Solution
There are many possible solutions for the task. We will solve this problem using array based approach.
Let's define a method signature:
public String reverseString(String input)
We would like the method to be visible to everyone, so we use public access modifier.
Because String class follows immutability principle, one cannot change an object of the class. That means we cannot modify an object which is referenced by input parameter. That's why we return another String object from reverseString method.
We need to change the order of chars in input. In order to do it we will create an array which represents the same word stored in input.
char[] array = new char[input.length()];
It creates a new array with the same length as the input word.
Okay we have an array but it does not contain anything yet (actually it has chars with 0 value). So let's fill in the array with the letters we want to be there:
for (int i = 0; i < input.length(); i++) {
array[i] = input.charAt(i);
}
Alternative. One of the reasons we like Java so much is that it can provide us a lot of wanted features for a little effort. Java has the above operations implemented already and you can just you the method:
char[] array = input.toCharArray();
Let's move on to the most important part the code which reverses the letters.
int lastArrayIndex = array.length - 1;
for (int i = 0; i < array.length / 2; i++) {
char temp = array[i];
array[i] = array[lastArrayIndex - i];
array[lastArrayIndex - i] = temp;
}
Here we go through the array from 1st element until the middle, and exchange an element with its opposite one. The opposite element is in a mirror position based on the middle of the array.

It also involves a temporary storage temp for the current element we are working on. Because we rewrite the current value we need to save original value somewhere to use it later.
You can ask: "why is lastArrayIndex required". Actually it's not required and can be inlined but you can create some meaningful variables which make your code more clear and easy to read. So this is the example when you can use them.
The final step is to convert the array to String object and return it to the method invoker.
return String.valueOf(array);
You can try to run this program following the link: https://onlinegdb.com/6LYPNZ6GQ
Thank you for you time!
Keep studying and have fun! Goodbye 👋