• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

StringBuffer/StringBuilder question - unexpected results

 
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi everyone, I am getting an exception on the following code and not sure why. Even in debug, there is nothing that indicates that the start position is out of bounds (start is at 128 while length is at 159 when the exception is thrown). The exception will follow the code.

public class TestStringBuffer {

public static void main(String[] args) {
String emptyString = new String(new byte[159]);
int[] sizes = new int[] {64, 64, 4, 1, 8, 10, 8};
String[] fields = new String[] {"test1", "test2", "ABC", "X", "ABCDEF", "123456", "qwerty" };
int start = 0;
StringBuilder newRec = new StringBuilder(emptyString);
for (int i = 0; i < fields.length; i++) {
String field = fields[i];
int end = start + sizes[i];
newRec.replace(start, end, field);
start = end;
}
}

}

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start > length()
at java.lang.AbstractStringBuilder.replace(Unknown Source)
at java.lang.StringBuilder.replace(Unknown Source)
at mycode.TestStringBuffer.main(TestStringBuffer.java:17)

Thanks in advance.
[ October 09, 2008: Message edited by: Patrick Williams ]
 
Sheriff
Posts: 22787
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You are replacing 64 characters with just 5 twice. It actually removes characters for this.

What you probably want is this:
 
Patrick Williams
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That did the trick. Thanks!
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic