Skip to content

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.

Output

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.

Output

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

Leave a Reply

Your email address will not be published.