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.
Methods of the StringTokenizer Class
The six useful methods of the StringTokenizer class are as follows:
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.
my name is khan
The above Java code, demonstrates the use of StringTokenizer class and its methods hasMoreTokens() and nextToken().
Example of nextToken(String delim) method of the StringTokenizer class
Next token is : my
Note: The StringTokenizer class is deprecated now. It is recommended to use the split() method of the String class or the Pattern class that belongs to the java.util.regex package.
Example of hasMoreTokens() method of the StringTokenizer class
This method returns true if more tokens are available in the tokenizer String otherwise returns false.
Demonstrating methods from StringTokenizer class
The above Java program shows the use of two methods hasMoreTokens() and nextToken() of StringTokenizer class.
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.
Hello everyone I am a Java developer
The above code demonstrates the use of hasMoreElements() method.
Example of nextElement() method of the StringTokenizer class
nextElement() returns the next token object in the tokenizer String. It can implement Enumeration interface.
Hello Everyone Have a nice day
The above code demonstrates the use of nextElement() method.
Example of countTokens() method of the StringTokenizer class
This method calculates the number of tokens present in the tokenizer String.
Total number of Tokens: 6
The above Java code demonstrates the countTokens() method of StringTokenizer() class.
Next TopicJava String FAQs