Saturday 7 May 2016

why to choose enum in java

why to choose enum in java

This are special data type that enables for a variable to set  predefined constants REF[1]

If you use enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use REF[2]


Let us take an example where you want to send the status code for service call requested.

ex :

define a service class which will take a request

# make a Http request.
@GET
#define the path for request.
@PATH(/voice)
#define mediatype to produce/consume
@Produces(MediaType.APPLICATION_JSON)
#start the service method
public Response VoiceResponse(){
ResponseBuilder responseBuilder = Response.status(ServerStatus.Server_Error);

}



Because they are constants, the names of an enum type's fields are in uppercase letters. REF[1]

define a class of enum type.

public enum ServerStatus {

#define status code
SUCCESS(200,'OK'),

#define server error.
Server_Error(500,'Internal server error')
}





REF :
1.oracle
2. stackoverflow

No comments:

Post a Comment