Reputation: 1313
I have the following method that normalises a given XML tag name:
public static String normaliseTagName(String tagName) {
// Return a given empty tag name.
if (tagName.length() == 0) {
return tagName;
}
// Replace invalid start.
if (isInvalidXMLStart(tagName.charAt(0))) {
tagName = XML_REPLACEMENT + tagName;
}
// Replace invalid characters.
StringBuilder normalised;
boolean invalidFound = false;
for (int i = 0; i < tagName.length(); i++) {
if (isInvalidXMLChar(tagName.charAt(i))) {
if (!invalidFound) {
normalised = new StringBuilder(tagName.substring(0, i));
invalidFound = true;
}
normalised.append(XML_REPLACEMENT); // COMPILER ERROR
} else if (invalidFound) {
normalised.append(tagName.charAt(i)); // COMPILER ERROR
}
}
return invalidFound ? normalised.toString() : tagName; // COMPILER ERROR
}
I don't want to initialise the StringBuilder normalised
before I'm sure to use it. In other words, I want to only initialise it when an invalid XML character is found.
I get The local variable normalised may not have been initialized
errors where indicated, and I'm puzzled as to why the compiler is telling me that when normalised
is clearly never used uninitialised.
StringBuilder normalised
in this situation?StringBuilder
only when I need it?Thanks!
Upvotes: 0
Views: 1421
Reputation: 48404
You need to explicitly initialize your local variable:
StringBuilder normalised = null;
... or ...
StringBuilder normalised = new StringBuilder();
... before referencing it.
Some of the pathways in your code reference normalised
prior to its initialization:
normalised.append(...
Local variables are not automatically initialized as would, instance fields.
Upvotes: 5