Reversing a string in Java is a common task used in programming for algorithm challenges, data manipulation, and text processing. Learning multiple methods helps write efficient and readable code.
public class ReverseStringExample1 { public static void main(String[] args) { String str = "JavaProgramming"; StringBuilder sb = new StringBuilder(str); String reversed = sb.reverse().toString(); System.out.println("Reversed string: " + reversed); } }
public class ReverseStringExample2 { public static void main(String[] args) { String str = "JavaProgramming"; char[] chars = str.toCharArray(); String reversed = ""; for(int i = chars.length - 1; i >= 0; i--) { reversed += chars[i]; } System.out.println("Reversed string: " + reversed); } }
public class ReverseStringExample3 { public static void main(String[] args) { String str = "JavaProgramming"; String reversed = ""; for(int i = str.length() - 1; i >= 0; i--) { reversed += str.charAt(i); } System.out.println("Reversed string: " + reversed); } }
public class ReverseStringExample4 { public static void main(String[] args) { String str = "JavaProgramming"; String reversed = reverseString(str); System.out.println("Reversed string: " + reversed); } public static String reverseString(String str) { if(str.isEmpty()) { return str; } return reverseString(str.substring(1)) + str.charAt(0); } }
| Method | Complexity | Ease of Use | When to Use |
|---|---|---|---|
| StringBuilder/StringBuffer | O(n) | Easy | Most efficient and recommended |
| Character Array | O(n) | Moderate | Understand manual string manipulation |
| For Loop | O(n²) if using String concatenation | Easy | Small strings or learning exercises |
| Recursion | O(n²) | Moderate | Learning recursion |
The simplest way is using StringBuilder.reverse() or StringBuffer.reverse().
Yes, you can reverse strings using for loops, character arrays, or recursion.
Yes, character case is preserved. "Java" becomes "avaJ".
Using StringBuilder or character array, it is O(n), where n is the length of the string.
Yes, converting a string to a character array allows in-place reversal without creating a new string object.
Reversing a string in Java is an essential skill with multiple methods available. While StringBuilder.reverse() is the most efficient, manual methods and recursion help strengthen programming fundamentals and problem-solving skills.
Copyrights © 2024 letsupdateskills All rights reserved