Home
Java
String Reverse
This page was last reviewed on Jan 9, 2022.
Dot Net Perls
Reverse string. A Java string contains a sequence of characters. To create another version of that string, we can reverse it. This can be used to form a string key.
Java method notes. We use many parts from Java to reverse a string. We create a mutable char array buffer. We use charAt to get (in inverse order) chars from the original string.
String charAt
Method example. We introduce the reverseString method. First we allocate a char array with a size equal to the string's length. Then we loop the array elements.
And We assign the array elements to a string character indexed from the opposite (inverted) side. This reverses the characters.
char Array
Finally We create a string and return it. In main we find that the reverseString works as expected on simple strings.
Constructor
public class Program { public static String reverseString(String value) { // Create a char buffer. char[] array = new char[value.length()]; for (int i = 0; i < array.length; i++) { // Assign to the array from the string in reverse order. // ... charAt uses an index from the last. array[i] = value.charAt(value.length() - i - 1); } return new String(array); } public static void main(String[] args) { // Test our reverse string method. String original = "abc"; String reversed = reverseString(original); System.out.println(original); System.out.println(reversed); original = "qwerty"; reversed = reverseString(original); System.out.println(original); System.out.println(reversed); } }
abc cba qwerty ytrewq
A discussion. The Arrays class has no reverse method. This means that we must reverse these characters manually. We find a reverse() on Collections.
But Collections.reverse would require the string be converted into a collection like an ArrayList. This would hinder performance.
ArrayList
Warning The tricky part with the reverseString method is the indexing expression into the string. This is the argument to charAt.
StringBuilder. Here is an alternative method. StringBuilder has a reverse method. We can create a StringBuilder from a string and then reverse it.
StringBuilder
A review. String reversal is not a common requirement. But for certain problems (like key generation) or for homework assignments, it has use.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 9, 2022 (image).
Home
Changes
© 2007-2024 Sam Allen.