Question

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.

  1. Am I missing something or is the compiler unable to determine the initialisation path of the StringBuilder normalised in this situation?
  2. If this compilation error cannot be avoided, how can I modify this code so that I initialise the StringBuilder only when I need it?

Thanks!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top