Appearance
Reverse a string in Java
To reverse a string in Java, you can use the following approaches:
- Using a
forloop:
Best for understanding the underlying logic or when you need custom iteration control.
java
public class Main {
public static void main(String[] args) {
String str = "Hello";
StringBuilder sb = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
sb.append(str.charAt(i));
}
String reversed = sb.toString();
System.out.println(reversed); // Output: "olleH"
}
}- Using the
reversemethod of theStringBuilderclass:
Recommended for most cases due to its readability and built-in optimization.
java
public class Main {
public static void main(String[] args) {
String str = "Hello";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(reversed); // Output: "olleH"
}
}- Using a character array swap:
Ideal for performance-critical scenarios where minimizing object allocation is important.
java
public class Main {
public static void main(String[] args) {
String str = "Hello";
char[] chars = str.toCharArray();
int left = 0;
int right = chars.length - 1;
while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
String reversed = new String(chars);
System.out.println(reversed); // Output: "olleH"
}
}I hope this helps! Let me know if you have any other questions.