Friday, August 28, 2009

No, my glasses do not need buffing. They just need a little javacast (StringBuffer gotcha)

I was working with the StringBuffer class earlier and ran into a small gotcha. I needed to create a StringBuffer with a capacity larger than default (16 characters). So I used one of the alternate constructors:

sb = createObject("java", "java.lang.StringBuffer").init( 256 );

As I tested the results, I noticed some numeric characters kept appearing at the end of the string. At first I thought was it was a mistake in my code. The base data did contain a lot of numbers. (Did I mention the string was reversed as well?). Yes, eventually I realized the value I kept seeing was .. wait for it .. the capacity value.

I was a bit surprised. The last time I checked 256 was a numeric value, and well within the range of Integer.MIN_VALUE and Integer.MAX_VALUE. However, there is another constructor for the StringBuffer class that accepts a java.lang.String and apparently that constructor won out in the "battle of the data types". So my object was initialized with the contents "256" rather than a capacity of 256 characters.

So lesson of the day: Sometimes it pays to use javacast. Even when you think you do not need it.


  © Blogger templates The Professional Template by 2008

Header image adapted from atomicjeep