How to Reverse the String in Java
Use the reverse method of the StringBuffer class in the JDK., Appending to a StringBuffer: StringBuffer is an apt choice to create and manipulate dynamic string information., A recursive function can also be used to reverse a string., CharArray can...
Step-by-Step Guide
-
Step 1: Use the reverse method of the StringBuffer class in the JDK.
The code snippet for reverse method is as follows: public String reverse(String str) { if ((null == str) || (str.length() <= 1)) { return str; } return new StringBuffer(str).reverse().toString(); } , Reversal using StringBuufer is also an option. public String reverse(String str) { if ((null == str) || (str.length() <= 1)) { return str; } StringBuffer reverse = new StringBuffer(str.length()); for (int i = str.length()
- 1; i >= 0; i--) { reverse.append(str.charAt(i)); } return reverse.toString(); } } , public String reverse(String str) { if ((null == str) || (str.length() <= 1)) { return str; } return reverse(str.substring(1)) + str.charAt(0); } , -
Step 2: Appending to a StringBuffer: StringBuffer is an apt choice to create and manipulate dynamic string information.
-
Step 3: A recursive function can also be used to reverse a string.
-
Step 4: CharArray can be used to reverse as follows: public String reverse(String str) { if ((null == str) || (str.length() <= 1)) { return str; } char[] chars = str.toCharArray(); int length = chars.length - 1; for (int i = 0; i < length; i++) { char tempVar = chars; chars= chars; chars= tempVar; } return new String(chars); }
Detailed Guide
The code snippet for reverse method is as follows: public String reverse(String str) { if ((null == str) || (str.length() <= 1)) { return str; } return new StringBuffer(str).reverse().toString(); } , Reversal using StringBuufer is also an option. public String reverse(String str) { if ((null == str) || (str.length() <= 1)) { return str; } StringBuffer reverse = new StringBuffer(str.length()); for (int i = str.length()
- 1; i >= 0; i--) { reverse.append(str.charAt(i)); } return reverse.toString(); } } , public String reverse(String str) { if ((null == str) || (str.length() <= 1)) { return str; } return reverse(str.substring(1)) + str.charAt(0); } ,
About the Author
Debra Morris
A seasoned expert in education and learning, Debra Morris combines 4 years of experience with a passion for teaching. Debra's guides are known for their clarity and practical value.
Rate This Guide
How helpful was this guide? Click to rate: