Difference between hasMoreElements() and hasMoreTokens() in StringTokenizer java

There is no difference between hasMoreElements() and hasMoreTokens() methods of StringTokenizer in Java.

StringTokenizer implements Enumeration interface and Enumeration interface has the below two methods

public interface Enumeration {
   boolean hasMoreElements();
   E nextElement();
}

As these two methods are in Enumeration interface and hence StringTokenizer has implementations of these two methods.

From functionality point of view , there is no difference between hasMoreElements() and hasMoreTokens().

Demo Example Using hasMoreTokens():

package com.canvera;
import java.util.StringTokenizer;
public class Main {
	public static void main(String[] args) {
         
		 StringTokenizer strTokenizer = new StringTokenizer("This is test program"," ");
		 System.out.println("Using hasMoreTokens() Method");
		 while(strTokenizer.hasMoreTokens()){
			 System.out.println(strTokenizer.nextToken());
		 }
		 System.out.println("------------------------------");
		 System.out.println("Using hasMoreElements() Method");
		 StringTokenizer strTokenizer1 = new StringTokenizer("This is test program"," ");
		 while(strTokenizer1.hasMoreElements()){
			 System.out.println(strTokenizer1.nextElement());
		 }
		
	}
}

Output of the above program is as below:

Using hasMoreTokens() Method
This
is
test
program
------------------------------
Using hasMoreElements() Method
This
is
test
program

Leave a Reply