Reversing a string is a common task in Java programming. In this article, we will discuss different ways to reverse a string in Java with examples.
String vs StringBuilder vs StringBuffer in Java Before we dive into the various methods of reversing a string in Java, let's understand some facts about the String, StringBuilder, and StringBuffer classes:
- String objects are immutable, i.e., once you create a string, you cannot modify its contents.
- The String class in Java does not have a reverse() method. However, the StringBuilder class has a built-in reverse() method.
- The StringBuilder class does not have a toCharArray() method, while the String class does have a toCharArray() method.
Now that we have a better understanding of the three classes, let's explore the different methods to reverse a string.
- Reverse a String using a loop The simplest method to reverse a string is to loop through it, extract each character, and add it to the beginning of the reversed string. Here is an example implementation:
rustpublic static String reverseString(String str) {
String reversedStr = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversedStr += str.charAt(i);
}
return reversedStr;
}
- Reverse a String using StringBuilder Since the StringBuilder class has a built-in reverse() method, we can easily reverse a string by first creating a StringBuilder object, adding the original string to it, and then calling the reverse() method. Here is an example implementation:
typescriptpublic static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
sb.reverse();
return sb.toString();
}
- Reverse a String using toCharArray() method The toCharArray() method in the String class converts a string to a character array. We can then loop through the array in reverse order and construct a new string. Here is an example implementation:
rustpublic static String reverseString(String str) {
char[] charArray = str.toCharArray();
String reversedStr = "";
for (int i = charArray.length - 1; i >= 0; i--) {
reversedStr += charArray[i];
}
return reversedStr;
}
- Reverse a String using swapping of variables We can also reverse a string by converting it to a character array and then swapping the characters at the start and end of the array. Here is an example implementation:
scsspublic static String reverseString(String str) {
char[] charArray = str.toCharArray();
int left = 0;
int right = charArray.length - 1;
while (left < right) {
char temp = charArray[left];
charArray[left] = charArray[right];
charArray[right] = temp;
left++;
right--;
}
return new String(charArray);
}
Conclusion In this article, we have discussed four different ways to reverse a string in Java. Depending on the use case, we can choose the method that best suits our requirements.