What is StringTokenizer.countTokens() in Java?

The countTokens method of the StringTokenizer class is an instance method that returns the number of remaining tokens that can be retrieved from a current position. This method also helps get all the tokens via the nextToken() method before nextToken generates an exception.

Based on the result of the hasMoreTokens() method, call the nextToken() method, as hasMoreTokens() helps check whether or not there are more tokens in the string tokenizer.

The StringTokenizer class is defined in the java.util package.

To import the StringTokenizer class, see the following import statement.

import java.util.StringTokenizer;

Syntax

public int countTokens()

Parameters

This method has no parameters.

Return value

countTokens() returns the count of tokens available from the current offset/position.

Code

In the below code, we define a string and a delimiter. We create an object of the StringTokenizer class and pass the string and delimiter. We then get the count of all available tokens. With the help of the token count obtained, we can get all the tokens using the nextToken method.

Read about the nextToken method here.

import java.util.StringTokenizer;
public class Main{
public static void main(String[] args){
String s = "hello-hi-educative";
StringTokenizer stringTokenizer = new StringTokenizer(s, "-");
int tokenCount = stringTokenizer.countTokens();
for(int i=0;i<tokenCount; i++){
System.out.println("Token [" + i + "] - " + stringTokenizer.nextToken());
}
}
}

Free Resources