String reversal is a fundamental problem frequently asked in coding interviews. we will explore multiple approaches to reverse a string in Java, with step-by-step explanations and practical code examples.
- 1. Using StringBuilder
Java provides StringBuilder
, which has a built-in reverse()
method to easily reverse a string.
public class ReverseStringExample { public static void main (String args []){ String str = "CodeSpeedy"; StringBuilder sb = new StringBuilder(str); sb.reverse(); // reverse the string System.out.println("Reversed String: " sb); } }
OUTPUT Reversed String: ydeepSedoC
2. Using a Character Array
In this method, we convert the string into a character array and swap the characters from start to end.
public class ReverseStringCharArray { public static void main (String args []){ String str ="Java" ; char[] charArray = str.toCharArray(); for (int i = 0, j = charArray.length - 1; i < j; i++, j--) { char temp = charArray[i]; charArray[i] = charArray[j]; charArray[j] = temp; } String reversedStr = new String(charArray); System.out.println("Reversed String: " + reversedStr); }
OUTPUT Reversed String: avaJ
- 3. Using Recursion
Recursion is a technique where a function calls itself until a base condition is met.
public class ReverseStringRecursion { public static String reverse(String str) { if (str.isEmpty()) return str; return reverse(str.substring(1)) + str.charAt(0); } public static void main(String[] args) { String str = "Hello"; System.out.println("Reversed String: " + reverse(str)); } }
OUTPUT Reversed String: olleH
- 4. Using a
for
LoopThis method iterates through the string in reverse order and constructs the reversed string.
public class ReverseStringLoop { public static void main(String[] args) { String str = "World"; String reversed = ""; for (int i = str.length() - 1; i >= 0; i--) { reversed += str.charAt(i); } System.out.println("Reversed String: " + reversed); } }
OUTPUT
Reversed String: dlroW
- 5. Using Stack (LIFO – Last In First Out)
A stack follows the Last In, First Out (LIFO) principle. We push each character into the stack and then pop them to get the reversed string.
import java.util.Stack; public class ReverseStringStack { public static void main(String[] args) { String str = "Code"; Stack<Character> stack = new Stack<>(); for (char c : str.toCharArray()) { stack.push(c); } String reversed = ""; while (!stack.isEmpty()) { reversed += stack.pop(); } System.out.println("Reversed String: " + reversed); } }
OUTPUT Reversed String: edoC