Home » Core Java » util » StringTokenizer » StringTokenizer Count Tokens

About Ilias Tsagklis

Avatar photo
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

StringTokenizer Count Tokens

This is an example of how to use a StringTokenizer to count the tokens of a String. The StringTokenizer is used to break a String into tokens. Using a StringTokenizer to count the tokens of a String implies that you should:

  • Get a new StringTokenizer for a specified String, using the StringTokenizer(String str) constructor.
  • Invoke countTokens() API method of StringTokenizer. The method calculates the number of times that this tokenizer’s nextToken() method can be called before it generates an exception, that is the number of tokens that the String of the tokenizer has.
  • While hasMoreTokens() API method of StringTokenizer returns true, invoke nextToken() method of StringTokenizer to get the tokens of this String and invoke countTokens() method again. Each time a new token is returned, the countTokens() method returns one less than before.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.util.StringTokenizer;

public class StringTokenizerCountTokens {
	public static void main(String[] args) {
		StringTokenizer tokenizer = new StringTokenizer("Java Code Geeks - Java Examples");
		System.out.println("Remaining Tokens: " + tokenizer.countTokens());
		// loop through tokens
		while (tokenizer.hasMoreTokens()) {
			System.out.println("Token:" + tokenizer.nextToken());
			System.out.println("Remaining Tokens: " + tokenizer.countTokens());



Remaining Tokens: 6
Remaining Tokens: 5
Remaining Tokens: 4
Remaining Tokens: 3
Remaining Tokens: 2
Remaining Tokens: 1
Remaining Tokens: 0

This was an example of how to use a StringTokenizer to count the tokens of a String in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments