On this document we will be showing a java example on how to use the hasMoreElements() method of StringTokenizer Class. The hasMoreTokens() method return the same value as that of hasMoreElements() method. You might be wondering what is the purpose of this method. This method is basically in place so that the StringTokenizer class would be able to implement the enumeration interface.

The hasMoreTokens() basically is a checker if the Tokenizer still has tokens available. This is actively being used in order to enumerate the tokens. While hasMoreTokens() works hand in hand with nextToken() method, the hasMoreElements() method works well with nextToken().

Method Syntax

public boolean hasMoreTokens()

Specified by:

hasMoreElements in interface Enumeration

Method Returns

The hasMoreElements() method returns true if there are more tokens; false otherwise.


Requires Java 1.0 and up

Java STringTokenizer hasMoreElements() Example

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


import java.util.StringTokenizer;

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

public class StringTokenizerHasMoreElementsExample {

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

		StringTokenizer tokenizer = new StringTokenizer(input,"$");
		// print all tokens


The above java example source code demonstrates the use of hasMoreElements() method of StringTokenizer class. Basically we just declared a new String object with tokens delimited by “$”. This made it possible by making use of one of the constructor of StringTokenizer class that accepts the String input and delimiter. Since the hasMoreElements() 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 nextElement() 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 hasMoreElements() example output