StringTokenizer Methods in Java



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

Sr.No Method & Description
1 int countTokens()
This method calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.
2 boolean hasMoreElements()
This method returns the same value as the hasMoreTokens method.
3 boolean hasMoreTokens()
This method tests if there are more tokens available from this tokenizer's string.
4 Object nextElement()
This method returns the same value as the nextToken method, except that its declared return value is Object rather than String.
5 String nextToken()
This method returns the next token from this string tokenizer.
6 String 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: 2019-09-20T11:32:32+05:30

318 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements