Java enum explained

Home - Tutorials - Basics

This article teaches you how to use an enum in Java. Code examples help you to understand the enumeration syntax.

Tutorial info:

Name:Java enum explained
Total steps:1
Product:See complete product

Bookmark Java enum explained

AddThis Social Bookmark Button

Step 1 - Java enum usage explained

Java enum explained

Prior Java 1.5 there was no real enums in the language. It was able to imitate the enum functionality but it was not type safe and there was no namespace to make the code more readable.

With Java 1.5 finally enum was arrived. You can simply define an enumeration using the enum keyword and the following syntax:

  1. public enum Color { BLACK, BLUE, GREEN, YELLOW, WHITE }

After you have defined an enum you can simply use it as any other type as you can see in this code example as well:

  1. public class EnumTest {
  2.     public enum Color { BLACK, BLUE, GREEN, YELLOW, WHITE }    
  4.     public static Color getColor(Color c) {
  5.         System.out.println("The color is:" + c);
  6.         return c;
  7.     }
  9.     public static void main(String[] args) {
  10.         Color myColor = getColor(Color.GREEN);
  11.         if (myColor == Color.GREEN) {
  12.             System.out.println("It is green!");
  13.         }
  14.     }    
  15. }


Tags: java enumeration, java enum, enum usage, how to use enum, java, enumeration, enum

Java enum explained - Table of contents
Step 1 - Java enum usage explained

Total time: 0.1793