ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Sample Java Source Code Program for String Tokenizer

Updated on November 1, 2013

Get A Website Plus a Free Domain Name in Just 1 Hour!

Bring the new technology in your hands! Share your skills, improve and impress. Get Your Own Website and a Free Domain Name Here!

Java Program: Use a String Tokenizer in Java with a Sample Java Source Code

What is a String Tokenizer and how to use it? String Tokenizer is a pre-defined class in Java which allows the String to be divided into tokens. Since the String Tokenizer is a class, in order to use it we must declare an ‘object’ to access the class. We will also use the hasMoreTokens() method of the class in order to check whether it still has tokens or none, and then use the nextToken() method to output the divided tokens of the String.

Where we can use string tokenizer?

I first used string tokenizer in sorting. It is beneficial especially if you don’t want to limit your program by declaring a size of the array or requesting size input from the user. The user will simply type the numbers as many as they want without worrying whether they already meet the size of the array or not.

By using String Tokenizer you are giving much freedom to the user to test your program excellently. It also minimizes the error that might produce by the program compare to the error that might produce when the program has a limited size.

Java Source Code for String Tokenizer


package stringtokenizer_in_java_programming;

import java.util.Scanner;
import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter a Sentence: ");
        String sentence = input.nextLine();


        StringTokenizer objectToken = new StringTokenizer(sentence);
        int token_count = 1;

        System.out.println();
        System.out.println("--See the Result of the Tokens of the Entered Sentence Below--");
        System.out.println();

       while(objectToken.hasMoreTokens())
       {
           System.out.println(objectToken.nextToken() + " -- Token # " + token_count);
           token_count++;

       }

    }

}

Sample Output:

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    Click to Rate This Article