Description

On this document we will be showing a java example on how to use the countTokens() method of StringTokenizer Class. The countTokens() calculates the number of times that this tokenizer’s nextToken method can be called before it generates an exception. The current position is not advanced.

Depending on the circumstances and what you want to achieve, this method is a good alternative in using the combination hasMoreTokens and nextToken(). The combination of countTokens and nextToken is handy if you are interested on the index of the tokens. However, it would be argued that this behaviour can also be achieved by using a counter variable during the iteration. Whatever the method and procedure may be, the most important to consider is the efficiency of the approach we should take.

Method Syntax

public int countTokens()

Method Returns

The countTokens() method returns the number of tokens remaining in the string using the current delimiter set.

Compatibility

Requires Java 1.0 and up

Java STringTokenizer countTokens() Example

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

package com.javatutorialhq.java.examples;

import java.util.StringTokenizer;

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

public class StringTokenizerCountTokensExample {

	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,"|");
		
		int count = st.countTokens();
		System.out.println("Number of tokens:"+count);
		
		for(int i = 0;i <count; i++){
			System.out.println("token["+i+"]="+st.nextToken());
		}
		
		
	}

}

The above java example source code demonstrates the use of coutTokens() 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. After which we have invoked the countTokens() method and assign it to the count variable. This variable have been used in framing the for-loop. Inside the for loop we have printed each token starting at 0 until the last token as checked the i < count statement.

Sample Output

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

java lang StringTokenizer countTokens() example output