Looking for java Answers? Try Ask4KnowledgeBase
Looking for java Keywords? Try Ask4Keywords

Java LanguageEnums


Introduction

Java enums (declared using the enum keyword) are shorthand syntax for sizable quantities of constants of a single class.

Syntax

  • [public/protected/private] enum Enum_name { // Declare a new enum.
  • ENUM_CONSTANT_1[, ENUM_CONSTANT_2...]; // Declare the enum constants. This must be the first line inside of the enum, and should be separated by commas, with a semicolon at the end.
  • ENUM_CONSTANT_1(param)[, ENUM_CONSTANT_2(param)...]; // Declare enum constants with parameters. The parameter types must match the constructor.
  • ENUM_CONSTANT_1 {...}[, ENUM_CONSTANT_2 {...}...]; // Declare enum constants with overridden methods. This must be done if the enum contains abstract methods; all such methods must be implemented.
  • ENUM_CONSTANT.name() // Returns a String with the name of the enum constant.
  • ENUM_CONSTANT.ordinal() // Returns the ordinal of this enumeration constant, its position in its enum declaration, where the initial constant is assigned an ordinal of zero.
  • Enum_name.values() // Returns a new array (of type Enum_name[]) containing every constant of that enum everytime it is called.
  • Enum_name.valueOf("ENUM_CONSTANT") // The inverse of ENUM_CONSTANT.name() -- returns the enum constant with the given name.
  • Enum.valueOf(Enum_name.class, "ENUM_CONSTANT") // A synonym of the previous one: The inverse of ENUM_CONSTANT.name() -- returns the enum constant with the given name.

Remarks

Restrictions

Enums always extend java.lang.Enum, so it is impossible for an enum to extend a class. However, they can implement many interfaces.

Tips & Tricks

Because of their specialized representation, there are more efficient maps and sets that can be used with enums as their keys. These will often run quicker than their non-specialized counterparts.