Monday, 6 October 2014

Java Enum and its different uses

Enums :-

  • are set of constants.
  • special type of class that extends java.lang.Enum
  • implements Comparable and Serializable, and singleton by default. Hence, we can compare  enum with == operator.
  • enforce compile time error check.

Simple implementation of enum

public enum Status {
ACT,
PEN,
ARC,
DAC
}

Here ACT, PEN, ARC, DAC all are constant for enum Status.


Enum with values 

We can provide value to enum at the time their creation, for this we need a private constructor and a private member variable.

public enum Status {
ACT("ACTIVE"),
PEN("PENDING"),
ARC("ARCHIVE"),
DAC("DEACTIVE");

private String value;
private Status(String value){
this.value = value;
}
public String getValue() {
return value;
}
}

usage:- Status.ACT.getValue();

Enum with abstract method

public enum Status {
ACT{
public String getDescription()
{
return "ACTIVE";
}
},
PEN{
public String getDescription()
{
return "PENDING";
}
},
ARC{
public String getDescription(){
return "ARCHIVE";
}
},
DAC{
public String getDescription(){
return "DEACTIVE";
}
};
public abstract String getDescription();
}

usage:- Status.ACT.getDescription();


Printing entire Enum 

for(Status s : Status.values()){
System.out.println((s.name()));
}


Handling IllegalArgumentException with Enum

Enum can throw illegalArguementException when we try to get value of anything which is not a part of enum set using valueOf().
This feature can be used to determine whether a particular value is a part of  enum set or not.
See below implementation.

public enum Status {
ACT,
PEN,
ARC,
DAC
}

public class ValidateStatus{

static String checkValidStatus(String status){
try{
Status.valueOf(status);
}
catch(IllegalArgumentException e){
return "Not a valid status";
}
return "valid status";
}
public static void main(String[] args) {

System.out.println(checkValidStatus("ACT"));
System.out.println(checkValidStatus("DEC"));
}

}

output:-
valid status
Not a valid status



No comments:

Post a Comment