✏️ Explanatory Question

[String Tokenizer]

Question:

What is the difference between the two methods, nextToken() and hasMoreTokens() of StringTokenizer class?


👁 0 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Answer:

1. nextToken()

The method:

nextToken()

is used to return the next token (word/string part) from the StringTokenizer object.

After returning a token, the tokenizer automatically moves to the next token.

Example:

StringTokenizer st = new StringTokenizer("Java is easy");

System.out.println(st.nextToken());

Output:

Java

2. hasMoreTokens()

The method:

hasMoreTokens()

checks whether more tokens are available or not.

It returns:

  • true → if tokens are still available
  • false → if no tokens remain

Example:

while(st.hasMoreTokens())
{
    System.out.println(st.nextToken());
}

This loop continues until all tokens are processed.


Difference Between the Methods:

nextToken()      → Returns next token

hasMoreTokens()  → Checks whether more tokens exist

Conclusion:

  • nextToken() extracts tokens one by one.
  • hasMoreTokens() is used for checking availability of tokens.
  • Both methods are commonly used together in loops.