What is StringTokenizer.nextToken() in Java?

The nextToken method of the StringTokenizer class is an instance method that returns the next token from the string tokenizer.

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

To import the StringTokenizer class, use the import statement below:

import java.util.StringTokenizer;

Syntax

public String nextToken​()

Parameters

The nextToken​() method takes no parameters.

Return value

The method returns the next token from the string tokenizer.

The method raises NoSuchElementException if the tokenizer’s string has no more tokens.

Code

In the code below:

  • We create an object of the StringTokenizer class, passing the string s and the delimiter -.

  • We use the hasMoreTokens() method to check if stringTokenizer has more tokens.

  • We use the nextToken() method to get each token.

import java.util.StringTokenizer;
public class Main{
public static void main(String[] args){
String s = "hello-hi-educative";
StringTokenizer stringTokenizer = new StringTokenizer(s, "-");
while(stringTokenizer.hasMoreTokens()){
System.out.println(stringTokenizer.nextToken());
}
}
}