StringTokenizer in Java
- The java.util.StringTokenizer class allows you to break a String into tokens. It is simple way to break a String. It is a legacy class of Java.
- It doesn’t provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.
- In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one to the tokens
Constructors of the StringTokenizer Class
There are 3 constructors defined in the StringTokenizer class.
StringTokenizer(String str) : It creates StringTokenizer with specified string.
StringTokenizer(String str, String delim) : It creates StringTokenizer with specified string and delimiter.
StringTokenizer(String str, String delim, boolean returnValue) : It creates StringTokenizer with specified string, delimiter and returnValue. If return value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens.
Methods of the StringTokenizer Class
The six useful methods of the StringTokenizer class are as follows:
- boolean hasMoreTokens() : It checks if there is more tokens available.
- String nextToken() : It returns the next token from the StringTokenizer object.
- String nextToken(String delim) : It returns the next token based on the delimiter.
- boolean hasMoreElements() : It is the same as hasMoreTokens() method.
- Object nextElement() : It is the same as nextToken() but its return type is Object.
- int countTokens() : It returns the total number of tokens.
Example of StringTokenizer Class
Let’s see an example of the StringTokenizer class that tokenizes a string “my name is khan” on the basis of whitespace.
Simple.java
Output:
Example of nextToken(String delim) method of the StringTokenizer class
Test.java
Output:
Example of hasMoreTokens() method of the StringTokenizer class
This method returns true if more tokens are available in the tokenizer String otherwise returns false.
Get Rushikesh Dudhane’s stories in your inbox
Join Medium for free to get updates from this writer.
StringTokenizer1.java
Output:
Example of hasMoreElements() method of the StringTokenizer class
This method returns the same value as hasMoreTokens() method of StringTokenizer class. The only difference is this class can implement the Enumeration interface.
StringTokenizer2.java
Output:
Example of nextElement() method of the StringTokenizer class
nextElement() returns the next token object in the tokenizer String. It can implement Enumeration interface.
StringTokenizer3.java
Output:
Example of countTokens() method of the StringTokenizer class
This method calculates the number of tokens present in the tokenizer String.
StringTokenizer3.java
Output:
Guide: http://www.vevcodelab.com/








