1

Is there any case where StringTokenizer.nextToken will return null? I'm trying to debug a NullPointerException in my code, and so far the only possibility I've found is that the string returned from nextToken() returned null. Is that a possibility? Didn't find anything in the java doc.

Thanks

duduamar
  • 3,816
  • 7
  • 35
  • 54
  • Are you sure you are not passing a null string to the constructor ? what does countTokens() return ? – Reno Jan 23 '11 at 09:55
  • To the constructor of StringTokenzier? I don't think so, doing so throws NullPointerException in the constructor itself, and this is not my case. – duduamar Jan 23 '11 at 10:03

2 Answers2

5

nextToken() throws NoSuchElementException if there are no more tokens in the tokenizer's string; so I would say that it doesn't return null.

http://download.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html#nextToken()

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
1

I think it can throw a NullPointerException.

Inspecting the code of nextToken(),

public String nextToken() {
        /*
         * If next position already computed in hasMoreElements() and
         * delimiters have changed between the computation and this invocation,
         * then use the computed value.
         */

        currentPosition = (newPosition >= 0 && !delimsChanged) ?
            newPosition : skipDelimiters(currentPosition);

        /* Reset these anyway */
        delimsChanged = false;
        newPosition = -1;

        if (currentPosition >= maxPosition)
            throw new NoSuchElementException();
        int start = currentPosition;
        currentPosition = scanToken(currentPosition);
        return str.substring(start, currentPosition);
    }

Here, invocation of the method skipDelimiters() can throw NullPointerException.

private int skipDelimiters(int startPos) {
        if (delimiters == null)
            throw new NullPointerException();

        int position = startPos;
        while (!retDelims && position < maxPosition) {
            if (!hasSurrogates) {
                char c = str.charAt(position);
                if ((c > maxDelimCodePoint) || (delimiters.indexOf(c) < 0))
                    break;
                position++;
            } else {
                int c = str.codePointAt(position);
                if ((c > maxDelimCodePoint) || !isDelimiter(c)) {
                    break;
                }
                position += Character.charCount(c);
            }
        }
        return position;
    }
aNish
  • 1,079
  • 6
  • 11