ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Java Source code: Reverse String in Java Using Recursion

Updated on February 23, 2013

Recursive Program on Reverse Letters/String

Reverse string in Java programming or printing a string backward using recursion is just a short program, which prompt the user to enter a string and the program output the last character up to the first character of the entered word. Originally, I used array on this but learned that it was not a wise decision so, I used the java predefined function charAt() instead. You can use charAt() if you want to extract a single character of the string. if you did not encounter charAt() yet, see the code below on how it works. Using charAt() is such a useful way to have a reverse string in java.

Java Source code: Reverse String in Java Programming

//Java source code on how to print a string backward using recursion

//java class

public class StringBackward
{
    public static void reverseString(String word, int size)
    {
       if(size==0)
       {
           return;
       }
       else
       {
          System.out.print(word.charAt(size-1));
          reverseString(word, size-1);
       }
    }

}

//main class

import java.util.Scanner;

public class Main {

    public static void main(String[] args)
    {
      Scanner input = new Scanner(System.in);

       String word;
       System.out.print("Enter a word: ");
       word = input.next();

        StringBackward access = new  StringBackward();
        System.out.print("The reverse word is: ");
        access.reverseString(word, word.length());
        System.out.println();

    }

}

Below is the sample output of the program.

Sample Output:

Enter a word: hubpages

The reverse word is: segapbuh

Sample Output 2:

Enter a word: hubbers

The reverse word is: srebbuh

This is just how the program works, you can also make this program as a reference for a palindrome test using boolean. If the program is palindrome or the reverse word is the same as the original word return true and if not return false.

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    Click to Rate This Article