StringTokenizer nextToken(String) in Java

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

Syntax:

String java.util.StringTokenizer.nextToken(String delim)

This method takes one argument. This method returns the next token in this string tokenizer's string. First, the set of characters considered to be delimiters by this StringTokenizer object is changed to be the characters in the string delim. Then the next token in the string after the current position is returned.

Parameters: One parameter is required for this method.

delim: the new delimiters.

Returns: the next token, after switching to the new delimiter set.

Throws:

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

2. NullPointerException - if delim is null

Approach 1: When no exception

Java

import java.util.StringTokenizer;

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

        System.out.println(stringTokenizer.nextToken("[a-z]"));
    }
}

Output:

Hello J


Approach 2: NoSuchElementException 

Java

import java.util.StringTokenizer;

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

        System.out.println(stringTokenizer.nextToken("[a-z]"));
    }
}

Output:

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



Approach 3: NullPointerException 

Java

import java.util.StringTokenizer;

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

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

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.StringTokenizer.skipDelimiters(StringTokenizer.java:245) at java.base/java.util.StringTokenizer.nextToken(StringTokenizer.java:341) at java.base/java.util.StringTokenizer.nextToken(StringTokenizer.java:376)



No comments:

Post a Comment