Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Method to return a String spelled backwards

807603Dec 14 2007 — edited Dec 14 2007
I'm trying to try a method that accepts a String object and displays its contents backwards.

Here is the method I wrote:
    public static String backwards(String word)
    {
        final int SIZE = word.length();

        char[] wordArray = word.toCharArray();  //converts String parameter to char array
        char[] backwardArray = new char[SIZE];

        for(int i = 0; i < SIZE; i++)
        {
            backwardArray[i] = wordArray[SIZE - i];
        }

        String backwardString = new String(backwardArray);

        return backwardString;
    }
I get the following exception thrown when I run the program:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
        at BackwardString.backwards(BackwardString.java:32)
        at BackwardString.main(BackwardString.java:16)
Press any key to continue . . .
There's probably an easy solution to this, but I don't see it. Could anybody help point me in the right direction?

Thanks.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 11 2008
Added on Dec 14 2007
14 comments
455 views