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...

4 Steps 1 min read Easy

Step-by-Step Guide

  1. 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); } ,
  2. Step 2: Appending to a StringBuffer: StringBuffer is an apt choice to create and manipulate dynamic string information.

  3. Step 3: A recursive function can also be used to reverse a string.

  4. 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

D

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.

30 articles
View all articles

Rate This Guide

--
Loading...
5
0
4
0
3
0
2
0
1
0

How helpful was this guide? Click to rate: