This post will discuss how to reverse a string using a character array in Java.

 
We know that we cannot make any change in the string object as string is immutable in Java. But we can use a character array that can be modified easily:

  1. Create an empty character array of the same size as that of the given string.
  2. Fill the character array backward with characters of the given string.
  3. Finally, convert the character array into string using String.copyValueOf(char[]) and return it.

The following program demonstrates it:

Download  Run Code

Output:

The reversed string is !em esreveR

Using swap():

Following is another efficient way to reverse a string in Java using character array:

  1. Create a character array and initialize it with characters of the given string using String.toCharArray().
  2. Start from the two endpoints l and h of the given string. Run the loop till two endpoints intersect (l <= h). In each iteration of the loop, swap values present at indexes l & h and increment l & decrement h.
  3. Finally, convert the character array into string using String.copyValueOf(char[]) and return.

The following program demonstrates it:

Download  Run Code

Output:

The reversed string is !em esreveR

That’s all about reversing a String using a character array in Java.