Java Enumeration Type java.lang.Enum class

Enumerations Inherit Enum

All enumerations automatically inherit java.lang.Enum class.

This class defines several methods for all enumerations.

To get a value that indicates an enumeration constant's position in the list of constants.

final int ordinal() 

To compare the ordinal value of two constants of the same enumeration by using the compareTo() method.

final int compareTo(enum-type e) 

// Use an enum constructor, instance variable, and method. 
enum Letter {//from  www .j a  va 2  s .  c om
  A(10), B(11), C(12), D(13), E(14);

  private int value; 

  // Constructor
  Letter(int p) {
    value = p;
  }
  int getValue() {
    return value;
  }
}

public class Main {
  public static void main(String args[]) {
    Letter ap, ap2, ap3; 
    
    ap =  Letter.A; 
    ap2 = Letter.C; 
    ap3 = Letter.D; 
 
 
    // Demonstrate compareTo() and equals() 
    if(ap.compareTo(ap2) < 0) 
      System.out.println(ap + " comes before " + ap2); 
 
    if(ap.compareTo(ap2) > 0) 
      System.out.println(ap2 + " comes before " + ap); 
 
    if(ap.compareTo(ap3) == 0) 
      System.out.println(ap + " equals " + ap3); 
   
    System.out.println(); 
 
    if(ap.equals(ap2)) 
      System.out.println("Error!"); 
 
    if(ap.equals(ap3)) 
      System.out.println(ap + " equals " + ap3); 
 
    if(ap == ap3) 
      System.out.println(ap + " == " + ap3);       
  }
}



PreviousNext

Related