1

I wrote this little function just for practice, but an exception ("String index out of range: 29") is thrown and I don't know why...

(I know this isn't the best way to write this function and can I use regular expressions.)

This is the code:

public String retString(String x) 
{
    int j=0;
    int i=0;
    StringBuffer y = new StringBuffer(x);

try
{


    while ( y.charAt(i) != '\0' )
    {
        if (y.charAt(i) != ' ')
        {
            y.setCharAt(j, y.charAt(i));
            i++;
            j++;
        }
        else
        {
            y.setCharAt(j, y.charAt(i));
            i++;
            j++;
            while (y.charAt(i) == ' ')
                i++;
        }           
    }
    y.setCharAt(j,'\0');



}
finally 
{

    System.out.println("lalalalololo " );
}

    return y.toString();


}

5 Answers 5

5

Are you translating this code from another language? You are looping through the string until you reach a null character ("\0"), but Java doesn't conventionally use these in strings. In C, this would work, but in your case you should try

i < y.length()

instead of

y.charAt(i) != '\0'

Additionally, the

 y.setCharAt(j,'\0')

at the end of your code will not resize the string, if that is what you are expecting. You should instead try

y.setLength(j)
2
  • Yup, doing that will have your program run perfectly +1.
    – Jimmy Huch
    Jun 11, 2011 at 23:23
  • pst y.setLength(j); will resize the string Jun 11, 2011 at 23:27
3

This exception is an IndexOutOfBoundsException but more particularly, a StringIndexOutOfBoundsException (which is derived from IndexOutOfBoundsException). The reason for receiving an error such as this is because you are exceeding the bounds of an indexable collection. This is something C/C++ does not do (you check bounds of collections manually) whereas Java has these built into their collections to avoid issues such as this. In this case, you're using the String object like an array (probably what it is in implementation) and going over the boundary of the String.

Java does not expose the null terminator in the public interface of String. In other words, you cannot determine the end of the String by searching for the null terminator. Rather, the ideal way to do this is by ensuring you do not exceed the length of the string.

0
2

Java strings are not null-terminated. Use String.length() to determine where to stop.

1

Looks like you are a C/C++ programmer coming to java ;)

Once you have gone out of range with .charAt (), it doesn't reach null, it reaches a StringIndexOutOfBoundsException. So in this case, you will need a for loop that goes from 0 to y.length()-1.

0
1

a much better implementation (with regex) is simply return y.replaceAll("\\s+"," "); (this even replaces other whitespace)

and StringBuffer.length() is constant time (no slow null termination semantics in java)

and similarly x.charAt(x.length()); will also throw a StringIndexOutOfBoundsException (and not return \0 like you'd expect in C)

for the fixed code:

while ( y.length()>i)//use length from the buffer
{
    if (y.charAt(i) != ' ')
    {
        y.setCharAt(j, y.charAt(i));
        i++;
        j++;
    }
    else
    {
        y.setCharAt(j, y.charAt(i));
        i++;
        j++;
        while (y.charAt(i) == ' ')
            i++;
    }           
}
y.setLength(j);//using setLength to actually set the length

btw a StringBuilder is a faster implementation (no unnecessary synchronization)

2
  • wow, thanks for this information I found good function just before I posted this function here (with regex) but I wanted to know what's wrong at my implementation. But thanks for the detailed answer ! Jun 11, 2011 at 23:42
  • and just for the record , the line while (y.charAt(i) == ' ') is also incorrect, it should be while ( (i < y.length() ) && (y.charAt(i) == ' ') ) :) Jun 11, 2011 at 23:49

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.