How do we reverse a string In Java?
In Java, there are several ways to reverse a string. Here are a few common methods:
StringBuilder
The StringBuilder
class has a built-in method called reverse()
that can be used to reverse a string easily.
public class ReverseString {
public static void main(String[] args) {
String original = "Hello, World!";
String reversed = new StringBuilder(original).reverse().toString();
System.out.println(reversed); // Output: !dlroW ,olleH
}
}
You can also reverse a string by iterating through it in reverse order and building a new string.
public class ReverseString {
public static void main(String[] args) {
String original = "Hello, World!";
String reversed = "";
for (int i = original.length() - 1; i >= 0; i--) {
reversed += original.charAt(i);
}
System.out.println(reversed); // Output: !dlroW ,olleH
}
}
You can convert the string to a character array, reverse the array, and then create a new string from the reversed array.
public class ReverseString {
public static void main(String[] args) {
String original = "Hello, World!";
char[] charArray = original.toCharArray();
String reversed = "";
for (int i = charArray.length - 1; i >= 0; i--) {
reversed += charArray[i];
}
System.out.println(reversed); // Output: !dlroW ,olleH
}
}
You can also reverse a string using a recursive method.
public class ReverseString {
public static void main(String[] args) {
String original = "Hello, World!";
String reversed = reverse(original);
System.out.println(reversed); // Output: !dlroW ,olleH
}
public static String reverse(String str) {
if (str.isEmpty()) {
return str;
}
return str.charAt(str.length() - 1) + reverse(str.substring(0, str.length() - 1));
}
}
These are some of the common methods to reverse a string in Java. The StringBuilder
method is generally the most efficient and straightforward way to achieve this.