In this article, we will write a recursive Java function reverse(String s) that returns the string s in reverse.
package com.topjavatutorial.app; import java.util.Scanner; public class StringReverse { public static void main(String[] args) { System.out.println("Enter a String: "); Scanner sc = new Scanner(System.in); String str = sc.next(); sc.close(); System.out.printf("Reverse of %s is %s", str, reverse(str)); } public static String reverse(String str) { if ((null == str) || (str.length() <= 1)) { return str; } // recursively add first char at end and reverse rest of the string return reverse(str.substring(1)) + str.charAt(0); } }
The function recursively adds the last character of the string to the end and reverses rest of the String.
So, this is what is does :
reverse(ello) + h
reverse(llo) + e
reverse(lo) + l
reverse(o) + l
Output :
Enter a String:
hello
Reverse of hello is olleh
Read more
© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post