Spot the bug… October 28, 2009Posted by Phill in Other Stuff.
Tags: bugs, java, operator precedence
Have you ever written something really stupid but not noticed it for ages?
Witness this statement of mine I wrote a month or so ago. The point of the code is to append a prefix to an existing description, or the empty string if the description is null.
description = prefix + " " + description == null ? "" : description;
Can you spot the error?
It turns out that Java was looking at this statement like this:
description = (prefix + " " + description) == null ? "" : description;
D’oh! Not what I intended! I changed the statement to put brackets round the description == null ternary statement and it seems to work.
Just goes to show, brackets are generally a good idea when making statements like this – it’s too easy to make mistakes with operator precedence otherwise!