Is it possible to assign a numeric value to an enum in Java?



Yes, it's possible to assign a numeric value to an enum.

Enum in Java is used to represent a list of predefined values. Most of the time, we probably not care about the associated value of an enum. However, there might be some times when we need to assign specific values to an enum.

Example:

import java.util.Enumeration;
import java.util.Vector;

public class EnumerationExample {
   public static void main(String[] args) {
      Vector vec = new Vector(4);
      vec.add(4);
      vec.add(3);
      vec.add(2);
      vec.add(1);
      Enumeration<Integer> e = vec.elements();
      System.out.println("Numbers in the enumeration are :- ");
      while (e.hasMoreElements()) {
          System.out.println("Number = " + e.nextElement());
      }
   }
}

Output:

Numbers in the enumeration are :-
Number = 4
Number = 3
Number = 2
Number = 1
raja
Published on 27-May-2019 16:05:55
Advertisements