StringTokenizer countTokens() Method in Java with Examples

The countTokens() method of StringTokenizer class calculate the number of times that this tokenizer’s nextToken method can be called before the method generates any further exception.
Note: The current position is not advanced during the process.

Syntax:

public int countTokens()

Parameters: The method does not take any parameters.



Return Value: The method is used to return the number of tokens remaining in the string using the current delimiter set.

Below programs illustrate the working of countTokens() Method of StringTokenizer:
Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to illustrate countTokens() method
  
import java.util.*;
  
public class StringTokenizer_Demo1 {
    public static void main(String args[])
    {
  
        // Creating a StringTokenizer
        StringTokenizer str_arr
            = new StringTokenizer(
                "Lets practice at GeeksforGeeks");
  
        // Counting the tokens
        int count = str_arr.countTokens();
        System.out.println("Total number of Tokens: "
                           + count);
  
        // Print the tokens
        for (int i = 0; i < count; i++)
            System.out.println("token at [" + i + "] : "
                               + str_arr.nextToken());
    }
}

chevron_right


Output:

Total number of Tokens: 4
token at [0] : Lets
token at [1] : practice
token at [2] : at
token at [3] : GeeksforGeeks

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to illustrate countTokens() method
  
import java.util.*;
  
public class StringTokenizer_Demo2 {
    public static void main(String args[])
    {
  
        // Creating a StringTokenizer
        StringTokenizer str_arr
            = new StringTokenizer(
                "Welcome to GeeksforGeeks");
  
        // Counting the tokens
        int count = str_arr.countTokens();
        System.out.println("Total number of Tokens: "
                           + count);
  
        // Print the tokens
        for (int i = 0; i < count; i++)
            System.out.println("token at [" + i + "] : "
                               + str_arr.nextToken());
    }
}

chevron_right


Output:

Total number of Tokens: 3
token at [0] : Welcome
token at [1] : to
token at [2] : GeeksforGeeks


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.