Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the advantage of using enum in java? [closed]

Tags:

java

enums

I was going through the enums in Java. It seems that the same things that enums can do can be achieved by collections or an array of Strings or user-defined types.

What is the main purpose of introducing enums in Java 5?

like image 681
user1720500 Avatar asked Dec 11 '22 19:12

user1720500


1 Answers

Advantages -

  • Set of Constant declaration
  • Restrict input parameter in method
  • Can be usable in switch-case

It is used for fields consist of a fixed set of constants.

Example is Thread.State

public enum State {
    NEW,
    RUNNABLE,
    WAITING,
    BLOCKED,
    ...
}

or private enum Alignment { LEFT, RIGHT };

You can restrict input parameter using Enum like-

String drawCellValue (int maxCellLnghth, String cellVal, Alignment align){}

Here in align parameter could be only Alignment.LEFT or Alignment.RIGHT which is restricted.

Example of switch-case with enum -

String drawCellValue (int maxCellLnghth, String cellVal, Alignment align){
    switch (align) {
    case LEFT:...
    case RIGHT: ...
    }
    ...
}
like image 135
Subhrajyoti Majumder Avatar answered Jan 06 '23 00:01

Subhrajyoti Majumder