Solution: There are many ways to do it, some of them are:
Using for loop
- Declare empty String
reverse
. This will contain our final reversed string. - Iterate over an array using for loop from
last
index to0th
index - Add character to String
reverse
while iterating.
package org.cloud.techtwitter.blogspot;public class ReverseStringForMain {public static void main(String[] args) {String blogName = "techTwitter";String reverse = "";for (int i = blogName.length() - 1; i >= 0; i--) {reverse = reverse + blogName.charAt(i);}System.out.println("Reverse of cloud.techtwitter is: " + reverse);}}
Using recursion
We can also use recursion to reverse a String in java
package org.cloud.techtwitter.blogspot;public class ReverseStringRecursive {public static void main(String[] args) {ReverseStringRecursive rsr = new ReverseStringRecursive();String blogName = "techTwitter";String reverse = rsr.recursiveReverse(blogName);System.out.println("Reverse of cloud.techtwitter is:" + reverse);}public String recursiveReverse(String orig) {if (orig.length() == 1)return orig;elsereturn orig.charAt(orig.length() - 1) +recursiveReverse(orig.substring(0, orig.length() - 1));}}
Don't miss the next article!
Be the first to be notified when a new article or Kubernetes experiment is published.