Skip to content

Solution – Java StringTokenizer java.lang.NullPointerException

Solution – Java StringTokenizer java.lang.NullPointerException example shows how to solve NullPointerException while using the StringTokenizer object.

How to solve NullPointerException while using the StringTokenizer object?

The NullPointerException is thrown by Java when we try to use an object reference that is null. For example, trying to call a method or trying to access an instance field of a null object reference.

The StringTokenizer class is used to generate tokens from the string content using the provided delimiter characters. A NullPointerException thrown by the StringTokenizer class is no different than the same exception thrown by any other class.

One possible could reason for this exception is that the string content we want to tokenize is null. See the below example that shows how that could be a problem.

Output

Solution: Make sure that the string data you want to tokenize is not null before creating the StringTokenizer object from it.

Another possible reason could be the delimiter being null. Please see below code example where I’ve passed a null value as a delimiter string in the constructor.

Output

As you can see from the output when the delimiter value is null, the StringTokenizer constructor does not throw the exception. It is when you try to access the hasMoreTokens method this exception is thrown.

Solution: Make sure that the specified delimiter string value is not null.

As a standard practice, always make sure to check for the null before using the object reference for any type of object to avoid the NullPointerException.

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.