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
Category:Basics
Date:2011-04-09
Level:Beginner
Product:See complete product
Viewed:8876

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:

Code:
  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:

Code:
  1. public class EnumTest {
  2.     public enum Color { BLACK, BLUE, GREEN, YELLOW, WHITE }    
  3.  
  4.     public static Color getColor(Color c) {
  5.         System.out.println("The color is:" + c);
  6.         return c;
  7.     }
  8.  
  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



F1 Site Family
AJAX F1
CSS F1
Database F1
HTML F1
Java F1
JavaScript F1
PHP F1

Total time: 0.1432