Enumeration is a list of named constants. Every most commonly used programming languages support this feature. But in Java it is officially supported since version 5.0. In Java programming language an enumeration defines a class type. Because an enumeration is a class it can have a constructors, methods, and instance variables.
To create an enumeration we use the enum
keyword. For example below is a simple enumeration that hold a list of notebook producers:
package org.kodejava.basic;
public enum Producer {
ACER, APPLE, DELL, FUJITSU, LENOVO, TOSHIBA
}
Below we use our enumeration in a simple program.
package org.kodejava.basic;
public class EnumDeclaration {
public static void main(String[] args) {
// Creates an enum variable declaration and assign the value to
// Producer.APPLE.
Producer producer = Producer.APPLE;
if (producer == Producer.LENOVO) {
System.out.println("Produced by Lenovo.");
} else {
System.out.println("Produced by others.");
}
}
}
The ACER
, APPLE
, DELL
identifiers are called enumeration constants. Every named constants have an implicitly assigned public and static access modifiers. Although the enumeration is a class type, to create an enumeration variable we don’t use the new
keyword. We create an enum
just like creating a primitive type of data, as you can see in the example above.
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024