Java Utility Library

Java StringTokenizer - countTokens() Method



The java.util.StringTokenizer.countTokens() method is used to calculate the number of times that this tokenizer's nextToken method can be called before it generates an exception. The current position is not advanced.

Syntax

public int countTokens()

Parameters

No parameter is required.

Return Value

Returns the number of tokens remaining in the string using the current delimiter set.

Exception

NA

Example:

In the example below, the java.util.StringTokenizer.countTokens() method is used to count the total number of tokens in the given string tokenizer.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a string tokenizer.
    StringTokenizer st = new StringTokenizer("Alpha,Coding,Skills",",");
   
    //printing total numbers of tokens
    System.out.println("Token Count is: " + st.countTokens());

    //printing tokens of the string tokenizer.
    System.out.println("StringTokenizer contains: ");
    while(st.hasMoreElements()) 
      System.out.println(st.nextElement());  
  }
}

The output of the above code will be:

Token Count is: 3
StringTokenizer contains: 
Alpha
Coding
Skills

❮ Java.util - StringTokenizer