tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Collection > Enum > Basic Operations

Basic Operations 

The following example shows how to perform basic operation with enum. All enum types implicitly implements java.io.Serializable and java.lang.Comparable. Enum provides the following APIs,

public static <E extends Enum<E>> E[] values();
 - Returns all enum constants of this element type. 
 
public final String name()
 - Returns name of enum constant.
 
public final int ordinal()
 - Returns position in its enum declaration starting with index ZERO.
 
public static <T extends Enum<T>> T valueOf(String name) 
 - Returns the enum constant of this enum type with the specified name.
   If no match found throws IllegalArgumentException.
  
public static <T extends Enum<T>> T valueOf(Class enumType, String name) 
 - Returns the enum constant of the specified enum type with the specified name.
   If no match found throws IllegalArgumentException.   


File Name  :  
com/bethecoder/tutorials/utils/enums/EnumBasicTests.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.utils.enums;

import java.util.Arrays;

public class EnumBasicTests {

  /**
   @param args
   */
  public static void main(String[] args) {

    /**
     * Get all enum constants of this type as array
     */
    Fruit [] fruits = Fruit.values();
    System.out.println(Arrays.toString(fruits));
    System.out.println();
    
    for (int i = ; i < fruits.length ; i ++) {
      System.out.println(fruits[i].name() "->" + fruits[i].ordinal());
    }
    
    /**
     * Get enum constant from Fruit enum class
     */
    System.out.println();
    Fruit fruit = Fruit.valueOf("MANGO");
    System.out.println(fruit);
    
    /**
     * Get enum constant from static method of Enum class
     */
    fruit = Enum.valueOf(Fruit.class, "APPLE");
    System.out.println(fruit);
    System.out.println();
    
    //Access invalid enum constant
    try {
      fruit = Fruit.valueOf("MANGO_BAD");
    catch (IllegalArgumentException e) {
      System.out.println(e);
    }
    
    //Access invalid enum constant
    try {
      fruit = Enum.valueOf(Fruit.class, "APPLE_BAD");
    catch (IllegalArgumentException e) {
      System.out.println(e);
    }
  }
  
}
   


File Name  :  
com/bethecoder/tutorials/utils/enums/Fruit.java 
   
package com.bethecoder.tutorials.utils.enums;

public enum Fruit {
  APPLE,
  ORANGE,
  BANANA,
  CHERRY,
  MANGO
}
   

It gives the following output,
[APPLE, ORANGE, BANANA, CHERRY, MANGO]

APPLE->0
ORANGE->1
BANANA->2
CHERRY->3
MANGO->4

MANGO
APPLE

java.lang.IllegalArgumentException: 
	No enum const class com.bethecoder.tutorials.utils.enums.Fruit.MANGO_BAD
java.lang.IllegalArgumentException: 
	No enum const class com.bethecoder.tutorials.utils.enums.Fruit.APPLE_BAD



 
  


  
bl  br