Suppose you have some text in Java that you want to manipulate. There are classes like StringBuffer for doing so, but let’s imagine that you choose to use a char array for some special reason.

Now suppose that several pages of code later, perhaps in a different piece of code entirely, you decide to use the value of the variable. At that point, you’ve forgetten that you didn’t use a StringBuffer, so you do the usual thing and call the toString() method.

Here’s some code to simulate what happens:

char []s = "Results of some computation".toCharArray();
// Lots of code later
System.out.println(s.toString());

When I compile and run the above, it outputs [C@1bc4459, which isn’t at all what you might hope.

There are two obvious questions which occur to me. The first is to wonder if this behavior of Java is deliberate. Is it considered useful in some way, or just an accident of implementation?

The second and more important question is: How can I detect such errors before code goes into production? Eclipse doesn’t catch it, and nor does PMD.