2

I am trying to reverse a string WITHOUT using StringBuilder. I have written the below code but it is giving an error as soon as it hits the loop. The error is

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 16
at lectures.ReverseString.main(ReverseString.java:38)

if anyone could tell me why that would be great. FYI I realize this code is not efficient or elegant but I want to know why it isn't working for education.

 public static void main(String[] args) {
    //declare variables
    Scanner input = new Scanner(System.in);
    String myString = "";
    int length = 0, index = 0, index2 = 0;

    //get input string
    System.out.print("Enter the string you want to reverse: ");
    myString = input.nextLine();

    //find length of string
    length = myString.length();
    index2 = length;

    //convert to array
    char[] stringChars = myString.toCharArray();
    char[] stringChars2 = stringChars;

    //loop through and reverse order
    while (index<length) {
        stringChars2[index] = stringChars[index2];
        index++;
        index2--;
    }

    //convert back to string
    String newString = new String(stringChars2);

    //output result
    System.out.println(newString);

    //close resources
    input.close();

}
3
  • 1
    It should be index2 = length - 1; remember arrays are indexed from 0 ... length - 1 Commented Oct 14, 2017 at 22:50
  • try using this: length = myString.length() - 1; Commented Oct 14, 2017 at 22:54
  • By the way, if I can give a suggestion, you don't need two arrays to do this. Just use a single array, with two index variables, and swap the first and the last characters, then swap the second and the next to last characters, etc... You keep doing that until your two indexes meet in the middle. Commented Oct 14, 2017 at 22:59

1 Answer 1

2

The last index in an array is not array.length but array.length - 1. Arrays are indexed on a zero-base, the first index is 0.

An array with two elements for example has indices [0] and [1], not [2].

You access, in the first iteration, stringChars[index2] and index2 = length where length = myString.length(). Thus the IndexOutOfBoundException. Carefully read through your code and analyze which indices you need. Create a small example, use some small print statements to debug your code and see which indices you are actually using.


Here is an example for a more compact reverse algorithm:

char[] input = ...

// Iterate in place, from both sides at one time
int fromFront = 0;
int fromEnd = input.length - 1;

while (fromFront < fromEnd) {
    // Swap elements
    char temp = input[fromEnd];
    input[fromEnd] = input[fromFront];
    input[fromFront] = temp;

    fromFront++;
    fromEnd--;
}

The algorithm swaps the element from the first position with the element from the last position in place. Then it moves one forward swapping the second element with the second to last and so on. It stops once both indices meet each other (if length is odd) or if the first index gets greater then the other (if length is even).

A more easy version, however without in-place, is to create a new array:

char[] input = ...
char[] reversedInput = new char[input.length];

// Reversely iterate through source
int forwardIndex = 0;
for (int i = input.length - 1; i > 0; i--) {
    reversedInput[forwardIndex] = input[i];
    forwardIndex++;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.