Java StringTokenizer – Get First & Last Tokens

Java StringTokenizer get the first and last tokens example shows how to get the first token and last token from the StringTokenizer object.

How to get the first token from the StringTokenizer?

Getting the first token from the StringTokenizer object is fairly easy. After creating a tokenizer object, check if there is any token available using the hasMoreTokens or hasMoreElements method. If it returns true, get the first token using the nextToken or nextElement method.

Here is the code example for that.


How to get the last token from the StringTokenizer object?

Getting the last token from the StringTokenizer object is not a straightforward thing to do. Since the StringTokenizer class does not provide any methods using which we can get a specific token by index, we need to iterate through all the tokens to get to the last one.

We are going to iterate through the string tokens using the hasMoreTokens and nextToken methods until there are no tokens left. See the below-given code example that does exactly that.


You may also want to know how to get the token ArrayList from the StringTokenizer or convert StringTokenizer to an array.

If you want to learn more about the tokenizer class, please visit the Java StringTokenizer Tutorial.

Please let me know your views in the comments section below.

About the author



My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *