On this document we will be showing a java example on how to use the hasMoreTokens() method of StringTokenizer Class. The hasMoreTokens() tests if there are more tokens available from this tokenizer’s string. If this method returns true, then a subsequent call to nextToken with no argument will successfully return a token

Depending on the circumstances and what you want to achieve, this method will achieve the same result as the combination of countTokens() and nextToken(). Basically if we don’t need to concern ourselves on the count of tokens, the hasMoreTokens is a good way to get the tokens.

Method Syntax

public boolean hasMoreTokens()

Method Returns

The hasMoreTokens() method returns true if and only if there is at least one token in the string after the current position; false otherwise.


Requires Java 1.0 and up

Java STringTokenizer hasMoreTokens() Example

Below is a java code demonstrates the use of hasMoreTokens() method of StringTokenizer class. The example presented might be simple however it shows the behaviour of the hasMoreTokens() method.


import java.util.StringTokenizer;

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

public class StringTokenizerHasMoreTokensExample {

	public static void main(String[] args) {
		//declare a new String with tokens delimited by |
		String input = "Beth|Ryan|Grace|Travis|Vince";
		 * initialize our StringTokenizer using input 
		 * as source String and | as the delimiter

		StringTokenizer st = new StringTokenizer(input,"|");
		// print all tokens


The above java example source code demonstrates the use of hasMoreTokens() method of StringTokenizer class. Basically we just declared a new String object with tokens delimited by “|”. We make use of one of the constructor of StringTokenizer class that accepts the String input and delimiter. Since the hasMoreTokens() check if there are still available tokens on the buffer, we can use this as a check on our while loop. The while loop will iterate until there are tokens available. And we used the nextToken() to get the current token and advance to the next one. The combination of this two are the fundamentals in using the StringTokenizer.

Sample Output

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

java lang StringTokenizer hasMoreTokens() example output