StringTokenizer Methods in Java with Examples | Set 2
StringTokenizer class in Java is used to break a string into tokens. One must go through StringTokenizer class where concepts and constructors are discussed which help in better understanding methods that are been discussed here below as follows:
Methods of StringTokenizer class are as follows:
Method 1: hasMoreTokens()
The method plays role in testing if tokens are present for the StringTokenizer’s string. Those characters that are considered to be delimiters by the StringTokenizer object are changed to characters in the string delimiter. Then the next token to the current position in the string is returned.
public boolean hasMoreTokens()
Return Type: A boolean value, true if and only if next token to the current position in the string exists, else false.
Method 2: nextToken()
The method returns the next token from the given StringTokenizer.
public String nextToken()
Return Type: The next token from the given StringTokenizer if present.
Exception Thrown: NoSuchElementException if no more tokens are left.
Method 3: countTokens()
The method returns the total number of tokens present so that we can use nextToken() method before it gives an exception.
public int countTokens()
Return Type: the number of tokens remaining in the string using the current delimiter set.
Number of tokens : 5 token at  : JAVA token at  : Code token at  : String token at  : Tokenizer token at  : Geeks
Method 4: nextElement()
The method works similar to nextToken except that it returns an Object rather than String. Exists so that this class can implement the Enumeration interface.
public Object nextElement()
Return Type: the next token from the given StringTokenizer.
Exception Thrown: NoSuchElementException if there are no more tokens left.
Method 5: hasMoreElements()
This method returns the same value as hasMoreToken. It exists so that the class can implement the Enumeration interface.
public boolean hasMoreElements()
Return Type: A boolean value, true if tokens are present in the string, else false
Number of tokens : 5 JAVA Code String Tokenizer Geeks
Tip: Do remember certain important points as listed:
- countTokens() method is a good alternative in using the combination hasMoreTokens() and nextToken().
- The combination of countTokens() and nextToken() is used if you are interested in the number of tokens also.
This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...