StringTokenizer nextToken() in Java

nextToken(): This method is available in java.util.StringTokenizer class of Java.

Syntax:

String java.util.StringTokenizer.nextToken()

This method returns the next token from this string tokenizer.

Parameters: NA

Returns: the next token from this string tokenizer.

Throws:

NoSuchElementException - if there are no more tokens in this tokenizer's string.

Approach 1: When no exception

Java

import java.util.StringTokenizer;

public class StringTokenizernextToken {
    public static void main(String[] args) {
        StringTokenizer stringTokenizer =
new StringTokenizer("Hello Java Program");

        System.out.println(stringTokenizer.nextToken());
    }
}

Output:

Hello


Approach 2: NoSuchElementException

Java

import java.util.StringTokenizer;

public class StringTokenizernextToken {
    public static void main(String[] args) {
        StringTokenizer stringTokenizer =
new StringTokenizer("");

        System.out.println(stringTokenizer.nextToken());
    }
}

Output:

Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.StringTokenizer.nextToken(StringTokenizer.java:348)


No comments:

Post a Comment