Reversing a string means changing its character order from end to start.
We will explore three different methods to reverse a string in Java.
This method iterates through the string from end to start and prints the characters.
public class ReverseStringLoop {
public static void reverseString(String s) {
for (int i = s.length() - 1; i >= 0; i--) {
System.out.print(s.charAt(i));
}
System.out.println();
}
public static void main(String[] args) {
String str = "hello";
reverseString(str);
}
}
This method reverses the string using recursion.
public class ReverseStringRecursion {
public static void reverseRecursively(String s, int index) {
if (index < 0) {
System.out.println();
return;
}
System.out.print(s.charAt(index));
reverseRecursively(s, index - 1);
}
public static void main(String[] args) {
String str = "world";
reverseRecursively(str, str.length() - 1);
}
}
This method uses the built-in StringBuilder reverse function to reverse the string.
public class ReverseStringBuilder {
public static void main(String[] args) {
String s = "example";
StringBuilder sb = new StringBuilder(s);
sb.reverse();
System.out.println(sb.toString());
}
}