Let’s go over string reversal in Java. There are several ways to reverse a string, from simple to more advanced. I’ll cover the most common methods.
1️⃣ Using a for
loop
public class StringReversal {
public static String reverseString(String str) {
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
return reversed;
}
public static void main(String[] args) {
String str = "Hello World";
System.out.println("Original: " + str);
System.out.println("Reversed: " + reverseString(str));
}
}
⚠️ Note: Using +=
in a loop is less efficient for long strings because strings are immutable.
2️⃣ Using StringBuilder
or StringBuffer
public class StringReversal {
public static void main(String[] args) {
String str = "Hello World";
// Using StringBuilder
String reversed = new StringBuilder(str).reverse().toString();
System.out.println("Original: " + str);
System.out.println("Reversed: " + reversed);
}
}
✅ This is more efficient than using a for
loop for long strings.
3️⃣ Using a Character Array
public class StringReversal {
public static String reverseString(String str) {
char[] chars = str.toCharArray();
int left = 0, right = chars.length - 1;
while (left < right) {
// Swap characters
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
return new String(chars);
}
public static void main(String[] args) {
String str = "Hello World";
System.out.println("Original: " + str);
System.out.println("Reversed: " + reverseString(str));
}
}
4️⃣ Recursive Method
public class StringReversal {
public static String reverse(String str) {
if (str.isEmpty()) return str; // Base case
return reverse(str.substring(1)) + str.charAt(0);
}
public static void main(String[] args) {
String str = "Hello World";
System.out.println("Original: " + str);
System.out.println("Reversed: " + reverse(str));
}
}
Notes:
- StringBuilder is generally the best choice for efficiency and readability.
- Recursive approach is elegant but can cause stack overflow for very long strings.
- Swapping using a char array is also memory-efficient.