Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum in Java. Advantages?

Tags:

What are some advantages of making enum in Java similar to a class, rather than just a collection of constants as in C/C++?

like image 787
gameover Avatar asked Jan 16 '10 14:01

gameover


People also ask

What is the advantage of using enum?

The benefits of using enumerations include: Reduces errors caused by transposing or mistyping numbers. Makes it easy to change values in the future. Makes code easier to read, which means it is less likely that errors will creep into it.

What is Java enum and what are the advantages of Java enum?

Java Enum (Enumerations) An enum is just like any other Java Class, with a predefined set of instances. It is basically a data type that lets you describe each member of a type in a more readable and reliable way, for example, temperature level like High, Medium and Low.

Why Enums are better than constants in Java?

Enums limit you to the required set of inputs whereas even if you use constant strings you still can use other String not part of your logic. This helps you to not make a mistake, to enter something out of the domain, while entering data and also improves the program readability.

What are the advantages of using an enum over an int?

The main benefit of enum is that constants can be referred to in a consistent, expressive and type safe way. Readability is of-course the topmost advantage of using the enumeration. Another advantage is that enumerated constants are generated automatically by the compiler.


1 Answers

You get free compile time checking of valid values. Using

public static int OPTION_ONE = 0;
public static int OPTION_TWO = 1;

does not ensure

void selectOption(int option) {
...
}

will only accept 0 or 1 as a parameter value. Using an enum, that is guaranteed. Moreover, this leads to more self documenting code, because you can use code completion to see all enum values.

like image 153
FRotthowe Avatar answered Oct 14 '22 20:10

FRotthowe