Header Ads

How To Get Values from Enum In Java

In my last post (http://www.mydigitalvoice.in/2013/05/enum-concept-simplified-in-java.html) I have shown how to declare enum in java. In this post we would see how to get values from enum rather how to get values from enum in a systematic approach.

There are three ways we can get values from enum..
  • direct way
  • by using values() method
  • by using ordinal() method

Direct Method
enum testenum21
{
JAN,FEB,MAR;
}
class getvalues{
public static void main(String... Args)
{
testenum21 mon=testenum21.JAN;
System.out.println(mon);
}
}

output: JAN
values() Method
We can use values method to get each element from enum.
The syntax is [[enumname]][] variable=[[enumname]].values();
enum testenum21
{
JAN,FEB,MAR;
}
class getvalues{
public static void main(String... Args)
{
testenum21[] mon=testenum21.values();
for(testenum21 m: mon)
{
System.out.println(m);
}
}
}

output:
JAN
FEB
MAR
ordinal() Method
If in our programming order of the enum constant becomes important,we can use ordinal method to get the order of the element.
The syntax is
public final int ordinal();
enum testenum21
{
JAN,FEB,MAR;
}
class getvalues{
public static void main(String... Args)
{
testenum21[] mon=testenum21.values();
for(testenum21 m: mon)
{
System.out.println(m+"..."+m.ordinal());
}
}
}
The output is
JAN...0
FEB...1
MAR...2
The ordinal method is more powerful and starts with zero. It is zero based.
Powered by Blogger.