Java enum, also called Java enumeration type, may be a type whose fields contains a hard and fast set of constants.
The java.lang.Enum.ordinal() tells about the ordinal number(it is that the position in its enum declaration, where the initial constant is assigned an ordinal of zero) for the actual enum.
ordinal() method may be a non-static method, it means it's accessible with the category object only and if we attempt to access the thing of another class it'll give the error. it's a final method, can't be overridden.
Syntax:
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()+" "); } } }
Output
Student Name: Rohit : 0 Geeks : 1 Author : 2
Code:
// 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 { james(3413), peter(34), sam(4235); 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() + " "); } System.out.println(); System.out.println("---------------------------"); for (Student_id id : Student_id.values()) { // printing all the value stored in the enum // index System.out.print("student Name : " + id + ": " + id.show()); System.out.println(); } } }
Output
Student Id List: james : 0 peter : 1 sam : 2 --------------------------- student Name : james: 3413 student Name : peter: 34 student Name : sam: 4235
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.