On this document we will be showing a java example on how to use the nextToken() method of StringTokenizer Class. The nextToken() method returns the next token from this string tokenizer. You might be wondering what is the purpose of this method. This method is basically in place as a way to traverse throughout the list of tokens.

This method is actively being used hand in hand with hasMoreTokens() method. When this two method are combined together, we will have a way to effectively traverse throughout the tokens.

Method Syntax

public String nextToken()


NoSuchElementException – if there are no more tokens in this tokenizer’s string.

Method Returns

The nextToken() method returns the next token from this string tokenizer.


Requires Java 1.0 and up

Java STringTokenizer nextToken() Example

Below is a java code demonstrates the use of nextToken() method of StringTokenizer class. The example presented might be simple however it shows the behaviour of the nextToken() method. Basically we have a string  declared initially and as you can see it’s actually a group of string delimited by “|” pipe. And we used StringTokenizer to break it down into tokens. This will transform the String into a more meaningful information on this case, we presented the first token as string, then the second as age, etc.


import java.util.StringTokenizer;

 * This example source code demonstrates the use of  
 * nextToken() method of StringTokenizer class.

public class StringTokenizerNextTokenExample {

	public static void main(String[] args) {
		//declare a new String with tokens delimited by |
		String str = "Vince|2|Male|Paya Lebar, Singapore";
		 * initialize our StringTokenizer using input 
		 * as source String and | as the delimiter

		StringTokenizer st = new StringTokenizer(str,"|");
		String name = st.nextToken();
		String age = st.nextToken();
		String gender = st.nextToken();
		String address = st.nextToken();


Sample Output

Below is the sample output when you run the above example.

java lang StringTokenizer nextToken() example output