Tuesday, July 9, 2013

Wizpert Chronicles: Tricky Strings

Introduction: I recently was recruited by Wizpert as a knowledgeable resource in the realm of Java programming (due to this blog, for the most part). I figure this is a nice way to help out other folks with Java programming problems. It also gives me good ideas for this blog! Here's one to get started.

The problem this time had to do with padding a string with zeroes. The code was checking the length of the string to see if padding was necessary:

if (s.length() == 5) { s = "0" + s; }

For some reason the zero was not being added. I suggested printing out the string with pipe characters around it, to check for whitespace. Sure enough:

|12345 |

An errant space was making the string length 6, causing the if test to fail. Looking back, I could have also suggested just printing out the value of s.length(), but sometimes it's nice to really see the issue directly.

Java strings provide a method trim() which, as it sounds, trims whitespace from the front and back of a string. However, it's not enough to just say:


Why not? Because trim() doesn't modify the original string. It returns a new string, which needs to then be assigned to a variable if you want to do something with it later.

s = s.trim();

That's better.

Strings are immutable objects in Java, so methods on them cannot change them. Instead, they return new objects. This sounds like it is a waste of memory and performance, but the benefits of immutability are worth it, and the JVM is optimized for handling many short-lived objects.