In this post, we will see java program to reverse a String.
There are many ways to do reverse a String in java, some of them are:
There are many ways to do reverse a String in java, some of them are:
Table of Contents
Using for loop
- Declare empty String
reverse
. This will contain our final reversed string. - Iterate over array using for loop from
last
index to0th
index - Add character to String
reverse
while iterating.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; public class ReverseStringForMain { public static void main(String[] args) { String blogName = "java2blog"; String reverse = ""; for (int i = blogName.length() - 1; i >= 0; i--) { reverse = reverse + blogName.charAt(i); } System.out.println("Reverse of java2blog is: " + reverse); } } |
Reverse of java2blog is: golb2avaj
💡 Did you know?
You can use
charAt(int index)
to access individual character in String.
Using recursion
We can also use recursion to reverse a String in java. We will process last character of String and call recursive function for rest of the String. Base case of the recursion will be once the length of String is 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package org.arpit.java2blog; public class ReverseStringRecursive { public static void main(String[] args) { ReverseStringRecursive rsr = new ReverseStringRecursive(); String blogName = "java2blog"; String reverse = rsr.recursiveReverse(blogName); System.out.println("Reverse of java2blog is:" + reverse); } public String recursiveReverse(String orig) { if (orig.length() == 1) return orig; else return orig.charAt(orig.length() - 1) + recursiveReverse(orig.substring(0, orig.length() - 1)); } } |
When you run above program, you will get following output:
Reverse of java2blog is:golb2avaj
Using StringBuffer
We can also simple use StringBuffer's
reverse()
method to reverse a String in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; public class StringBufferReverse { public static void main(String[] args) { String blogName = "java2blog"; StringBuffer sb = new StringBuffer(blogName); System.out.println("Reverse of java2blog is:" + sb.reverse()); } } |
When you run above program, you will get following output:
Reverse of java2blog is:golb2avaj
Please go through java interview programs for more such programs.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.
great resource. I have learned java a bit but its forgetting very soon. it’s a good refresh for me
I can’t find any better java tutorial than java2blog. Thank you Arpit.