Skip to content

Solution – Java StringTokenizer java.util.NoSuchElementException

Solution – Java StringTokenizer java.util.NoSuchElementException example shows how to solve NoSuchElementException while using the StringTokenizer object.

How to solve java.util.NoSuchElementException while using the StringTokenizer object?

The StringTokenizer class in Java creates string tokens from the provided content and the delimiter values. Once these tokens are generated we can access these tokens using the nextToken or nextElement methods.

See below-given code example that shows how it works.


The nextToken method advances internal position to the next delimiter found in the string data. So when we call the nextToken method again, it returns the next token in the content.

The NoSuchElementException exception is thrown by Java when we call the nextToken method but there are no more tokens to be fetched from the tokenizer. See the below example to understand it.


In the above example, I called the nextToken method two times but there was only one token in the string content.


The StringTokenizer class provides the hasMoreTokens method just for that purpose. It returns true if there are more tokens available to fetch, false otherwise.

Always call this method to check for more tokens before calling the nextToken method as shown in the below example.


Never call the nextToken method before checking the availability of more tokens to make sure that this exception is never thrown by the code.

If you want to learn more about the tokenizer, please visit the Java StringTokenizer tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.