Important Functions You Should Know From Java Enum

In the previous session we have seen the things which we don’t know about Java Enum. In this session we will see two important methods which is available in Enum.

Important Functions You Should Know From Java Enum

Java Enum – Ordinal Method

This method will return Ordinal value of Enum Constant. It will start from 0. Let’s see with some example.

package com.learnfromexamples.enumtutorial.pkg2;
public class SignalImplementation {

 enum Season{
       SPRING, SUMMER, AUTUMN, WINTER
 }

 public static void main(String[] args) {
       System.out.println(Season.SPRING.ordinal());
       System.out.println(Season.SUMMER.ordinal());
       System.out.println(Season.AUTUMN.ordinal());
       System.out.println(Season.WINTER.ordinal());
  }
}

Output


0
1
2
3

If we see the output, it print the ordinal value of each Enum Constant. 0 for Spring Enum Constant, 1 for Summer Enum Constant and so on.

Java Enum – Values Method

Values method will return all the Enum Constant in an Array. Let’s see this with one example.


package com.learnfromexamples.enumtutorial.pkg2;

public class SignalImplementation {
 enum Season{
       SPRING, SUMMER, AUTUMN, WINTER
 }

 public static void main(String[] args) {
       Season[] arrayOfSeasons = Season.values();
       for(Season season : arrayOfSeasons){
           System.out.println("Season Name is :" + season);
       }
   }
}

Output


Season Name is :SPRING
Season Name is :SUMMER
Season Name is :AUTUMN
Season Name is :WINTER

Read Also:

How to use Java Enum in Switch Case Statement -Example – Click here

How to convert String to Java Enum and Java Enum to String – Click here

Java Enum Basic Tutorial with Example – Click Here

We have seen two important methods in Enum. But Is there any method to convert String to Enum and Enum to String. Yes, We will see those in our next session.

If you have any questions on this blog, please ask your question in the comment box. If you like this blog, please share it with your friends and as well as comment your feedback.