StringTokenizer methods in Java


The StringTokenizer class allows an application to break a string into tokens. Following are the methods −

Sr.NoMethod & Description
1int countTokens()
This method calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.
2boolean hasMoreElements()
This method returns the same value as the hasMoreTokens method.
3boolean hasMoreTokens()
This method tests if there are more tokens available from this tokenizer's string.
4Object nextElement()
This method returns the same value as the nextToken method, except that its declared return value is Object rather than String.
5String nextToken()
This method returns the next token from this string tokenizer.
6String nextToken(String delim)
This method returns the next token in this string tokenizer's string.

Let us see some of the examples of the StringTokenize class displaying the usage of its method −

Here, we are using the countTokens() method to calculate the number of times that this tokenizer's nextToken method can be called before it generates an exception −

Example

import java.util.*;
public class Main {
   public static void main(String[] args) {
      // creating string tokenizer
      StringTokenizer st = new StringTokenizer("Welcome to my website!");
      // counting tokens
      System.out.println("Total tokens : " + st.countTokens());
   }
}

Output

Total tokens : 4

Now, let us see another example wherein we are using the nextElement() method. The nextElement() method is used to return the same value as the nextToken method, except that its declared return value is Object rather than String −

Example

import java.util.*;
public class Main {
   public static void main(String[] args) {
      // creating string tokenizer
      StringTokenizer st = new StringTokenizer("This is it!");
      // moving to next element
      st.nextElement();
      // checking next to next element
      System.out.println("Next element is : " + st.nextElement());
   }
}

Output

Next element is : is

Updated on: 20-Sep-2019

262 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements