Open In App
Related Articles

Java Program to Define Ordinal() Method Using Enum Concept

Improve Article
Save Article
Like Article

Java enum, also called Java enumeration type, is a type whose fields consist of a fixed set of constants. 

The java.lang.Enum.ordinal() tells about the ordinal number(it is the position in its enum declaration, where the initial constant is assigned an ordinal of zero) for the particular enum.

ordinal() method is a non-static method, it means that it is accessible with the class object only and if we try to access the object of another class it will give the error. It is a final method, cannot be overridden.


public final int ordinal();

Return Value:

This method returns the ordinal of this enumeration constant.

Default Value of the Enum is 0 and increment upto the index present in enum.

Like we have declare three index in enum class So the ordinal() value for the enum index is 0, 1, 2

Code For the Default ordinal position for Enum:


// Java program to show the usage of
// ordinal() method of java enumeration
import java.lang.*;
 import java.util.*;
// enum showing Student details
enum Student {
   Rohit, Geeks,Author;
public class GFG {
   public static void main(String args[]) {
      System.out.println("Student Name:");
      for(Student m : Student.values()) {
         System.out.print(m+" : "+m.ordinal()+" ");


Student Name:
Rohit : 0 Geeks : 1 Author : 2

We can also store the value to the index present in the enum but the ordinal value will remain the same. It will not be altered.



// Java program to show that the ordinal
// value remainw same whether we mention 
// index to the enum or not
import java.lang.*;
import java.util.*;
// enum showing Mobile prices
enum Student_id {
    int id;
    Student_id(int Id) { id = Id; }
    public int show() { return id; }
public class GFG {
    public static void main(String args[])
        // printing all the default ordinary number for the
        // enum index
        System.out.println("Student Id List: ");
        for (Student_id m : Student_id.values()) {
            System.out.print(m + " : " + m.ordinal() + " ");
        for (Student_id id : Student_id.values()) {
            // printing all the value stored in the enum
            // index
            System.out.print("student Name : " + id + ": "


Student Id List: 
james : 0 peter : 1 sam : 2 
student Name : james: 3413
student Name : peter: 34
student Name : sam: 4235

Last Updated : 27 Nov, 2020
Like Article
Save Article
Similar Reads
Related Tutorials