Java Enum

Enum is a short form of "Enumeration". Enum is one kind java class that may have attributes and methods like regular java class. But, enum attributes are constants. Means, unchangeable. Attributes are by default public, static, final. You can't modify the enum attributes.

Note: Enum is created using the enum keyword following the enum name and the attributes inside enum should be uppercase letters. (Recommended but not required, because they are unchangeable)

# Creating and access enum attributes


enum Colors{ //name of Enum
  RED,
  BLUE,
  YELLOW
}

public class Main{ //file name
  public static void main (String[] args) {
    System.out.println(Colors.RED);
    //or 
    Colors redColor = Colors.RED;
    System.out.println(redColor);
  }
}
/**
 * RED
 * RED
 */
 

# Enum can also be created inside a java class.


public class Main{ //file name
  
  enum Colors{ //name of Enum
   RED,
   BLUE,
   YELLOW
}
  public static void main (String[] args) {
    System.out.println(Colors.RED);
    //or 
    Colors redColor = Colors.RED;
    System.out.println(redColor);
  }
}
/**
 * RED
 * RED
 */

# Using for loop

Let's use for loop to iterate the enum const attributes.


enum Colors{
  RED,
  BLUE,
  YELLOW
}

public class Main{ //file name
  public static void main (String[] args) {
    
    for(int i = 0; i < Colors.values(). length; i++){
      System.out.println(Colors.values()[i]);
    }
  }
}
/**
 * RED
 * BLUE
 * YELLOW 
 */

Note: Enum has a special values() method that returns all the values (constant fields) of an enum.

# Loop through enum using for each loop.


enum Colors{
  RED,
  BLUE,
  YELLOW
}

public class Main{ //file name
  public static void main (String[] args) {
    
    //using for each loop
    for(Colors colors: Colors.values()){
      System.out.println(colors);
    }
  }
}
/**
 * RED
 * BLUE
 * YELLOW 
 */

//This is an ongoing article.
//Thanks for reading this article.