Enumeration nextElement() Method in Java with Examples

An object that implements the Enumeration interface generates a series of elements, one at a time. The nextElement() method of Enumeration used to return the next element of this enumeration if this enumeration object has at least one more element to provide.This method is used to get elements from the enumuration.

Syntax:

E nextElement()

Parameters: This method accepts nothing.

Return value: This method returns true the next element of this enumeration.

Exception: This method throws NoSuchElementException if no more elements exist.

Below programs illustrate nextElement() method:
Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// Enumeration.nextElement() method
  
import java.util.*;
  
public class GFG {
  
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] args)
    {
  
        // create a Enumeration and vector object
        Enumeration<Integer> company;
        Vector<Integer> employees = new Vector<Integer>();
  
        // add values to employees
        employees.add(1001);
        employees.add(2001);
        employees.add(3001);
        employees.add(4001);
        company = employees.elements();
  
        while (company.hasMoreElements()) {
            // get elements using nextElement()
            System.out.println("Emp ID = "
                               + company.nextElement());
        }
    }
}

chevron_right


Output:

Emp ID = 1001
Emp ID = 2001
Emp ID = 3001
Emp ID = 4001

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// Enumeration.nextElement() method
  
import java.util.*;
  
public class GFG {
  
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] args)
    {
  
        // create a Enumeration and vector object
        Enumeration<String> Users;
        Vector<String> user = new Vector<String>();
  
        // add Users
        user.add("Aman Singh");
        user.add("Raunak Singh");
        user.add("Siddhant Gupta");
        Users = user.elements();
  
        while (Users.hasMoreElements()) {
            // get elements using nextElement()
            System.out.println(Users.nextElement());
        }
    }
}

chevron_right


Output:

Aman Singh
Raunak Singh
Siddhant Gupta

References: https://docs.oracle.com/javase/10/docs/api/java/util/Enumeration.html#nextElement()



My Personal Notes arrow_drop_up

I am a Developer I love to code and bring my ideas alive

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.